﻿//---------------------------------------------------------------------------
#include "Main_Form.h"
#include <math.h>
#include <vcl.h>
#include <ctype.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <time.h>
#include <Inifiles.hpp>
//#include "I2C_Comm.h"
#include "I2CDriver.h"
#pragma hdrstop
#include "Main_Form.h"
#include "Check_Item.h"
#include "psword.h"
#include "Set_Freq.h"
#include "Set_Rev.h"
#include "Address_Setting.h"
#include "SN_Check.h"
#include "Com_Function.h"
//#include "GY7601_I2C.h"
#include "I2C_Interface.h"
#include "USB_845x.h"
#include "OltMes.h"
#include <ADODB.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
#define COL_CYCLE 26

#define _24LC064 0
#define CSV_FILE_GENERATE 1

// extern IpcMes;       11
int SlaveAddress = 0xB0;
String hostIP, Mark2B, Fru_Model = "U1A-D10800-DRB-F.ini";
#if CSV_FILE_GENERATE
String StreamFileName = Application->Title.UpperCase() + ".cnt";
String ConntCsvName = Application->Title.UpperCase() + ".csv";

#endif
long int time_write, time_read;
String Com_port = "COM1";

char str[8];
const char szColCycle[COL_CYCLE] = {
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
		'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
		'U', 'V', 'W', 'X', 'Y', 'Z'
    };

extern bool I2C_Interface_FLAG, Label_Check_Result, Continue;
bool EnableAspowerEepUnlock = false;
bool bAutoExitFlag = false;
extern AnsiString Label_File_Name;
bool Check_Result, FirstTime, Check_Data;
int I2C_Frequency, SaveData, EEPROM_Address, WriteOrRead;
int Rev_Count = 3, Rev_Address = 0x42;
int SN_Count = 14, SN_Address = 0x46;			  //SN PSGC04H10017
int Name_Count = 16, Name_Address = 0x24;		  //Model Name
int Model_No_Count = 14, Model_No_Address = 0x24; //pn
int Mfr_SN_Count = 13, Mfr_Sn_Address = 0x47;
int Mfr_Date_Count = 8, Mfr_Date_Address = 0x57;
int MaskAddrTable[30] = {0x00, 0x00, 0x00};
int MaskAddrNum = 0x00;
int Chksum1_Begin = 0x18, Chksum1_End = 0x56, Chksum1_Loct = 0x57;
bool EEP_Mirror_Enable = false; //this means the block of 128~255 is the same to 00~127
bool PNSupport = false;			//bool PNSupport = true;
bool TimeSupport = false;
int Time_No_Count = 3, Time_No_Address = 0x0B;
AnsiString PassWord_str, I2C_Interface, RevStr, strLog;
SaveAtRemoteFolder* PMLogSave;      //Parameter
SaveAtRemoteFolderResponse* PLogRet;
byte Write_sn[20] = {0};
String ModelTypes[20];

byte u8ReadBufferArray2[20] = {0};
int FRU_Data[300] =
	/*               0    1    2    3    4    5    6    7    8    9    A    B    C    D    E    F          */
	/*00*/ {
                    0x01, 0x01, 0x00, 0x00, 0x03, 0x0B, 0x00, 0xF0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x19, 0xC7, 0x41, 0x53, 0x50, 0x20,
                    0x20, 0x20, 0x20, 0xD0, 0x55, 0x31, 0x41, 0x2D, 0x44, 0x31, 0x30, 0x38, 0x30, 0x30, 0x2D, 0x44,
                    0x52, 0x42, 0x2D, 0x46, 0xCC, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
                    0x20, 0xC3, 0x31, 0x2E, 0x30, 0xCE, 0x41, 0x44, 0x30, 0x38, 0x30, 0x48, 0x44, 0x34, 0x36, 0x30,
                    0x30, 0x30, 0x30, 0x31, 0xC0, 0xC0, 0xC1, 0x89, 0x00, 0x02, 0x18, 0x3A, 0xAC, 0x20, 0x03, 0x20,
                    0x03, 0x37, 0x05, 0x10, 0x27, 0x9C, 0x31, 0x50, 0x46, 0x20, 0x67, 0x2F, 0x3F, 0x0C, 0x1E, 0x20,
                    0xC3, 0x00, 0x20, 0x03, 0x85, 0x01, 0x02, 0x0D, 0x78, 0x78, 0x01, 0xB0, 0x04, 0x74, 0x04, 0xEC,
                    0x04, 0x78, 0x00, 0xF4, 0x01, 0xFF, 0xFF, 0x01, 0x82, 0x0D, 0xAE, 0xC2, 0x82, 0xB0, 0x04, 0x74,
                    0x04, 0xEC, 0x04, 0x78, 0x00, 0x00, 0x00, 0x34, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
			};

String Bom99 = "99MAD10800I1170121";
String Date_Compiled = GetDateCompiled();
String Address_Enum;
String sTips;
TI2CDriver *I2CDriver = new TI2CDriver();
TMainForm *MainForm;
//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent *Owner)
	: TForm(Owner)
{
	PMLogSave = new SaveAtRemoteFolder();
    PMLogSave->user = L"TestHostCom";
    PMLogSave->pwd = L"0000";
    ModelTypes[0] = "99MAD10800I1170121";
	ModelTypes[1] = "910908000000222";
//	Fru_Model = Bom99;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FormCreate(TObject *Sender)
{
	int i, j, SerialNumbers[8];
	AnsiString TextBuf;
    String buf;

	IpcMes->sConfigFileName = ExtractFilePath(Application->ExeName) + "MES.ini";
	IpcMes->GetConfigFromIniFile();

	Open_Ini_File(ExtractFilePath(Application->ExeName) + Fru_Model);
    htpr1->Port = L"ServiceSaveFileSoap12";
    htpr1->Service = L"ServiceSaveFile";
	I2C_Interface_FLAG = true;
	//I2C_Interface="MCP" ;

	if (IpcMes->bMesIsEnabed)
	{
		TfrmMes *frm = new TfrmMes(this);
		frm->ShowModal();
		delete frm;
	}
	//if(I2C_Interface=="ISA")
	//  Initial_ISA_Intreface();
	// else if(I2C_Interface=="USB")
	if (I2C_Interface == "GY7601")
	{
		ISA->Checked = true;
		USB->Checked = false;
	}
		else if (I2C_Interface == "NI8451")
	{
		NI8451->Checked = true;
	}
	else
	{
		USB->Checked = True;
		ISA->Checked = false;
	}

	Initial_USB_Intreface();

    buf = RevStr;
    if (false == ValidateRevStr(buf))
    {
    	Application->MessageBoxA(buf.w_str(), L"Error", MB_OK|MB_ICONWARNING);
        this->RevClick(Sender);
        return;
    }

	Source_StringGrid->ColCount = 17;
	Source_StringGrid->RowCount = 17;
	Reading_StringGrid->ColCount = 17;
	Reading_StringGrid->RowCount = 17;
	for (i = 0; i < 17; i++)
	{
		Source_StringGrid->RowHeights[i] = 18;
		Source_StringGrid->ColWidths[i] = 20;
		Reading_StringGrid->RowHeights[i] = 18;
		Reading_StringGrid->ColWidths[i] = 20;
	}
	for (i = 0; i < 16; i++)
	{
		Source_StringGrid->Cells[i + 1][0] = IntToHex(i, 2);
		Source_StringGrid->Cells[0][i + 1] = IntToHex(i * 16, 2);
		Reading_StringGrid->Cells[i + 1][0] = IntToHex(i, 2);
		Reading_StringGrid->Cells[0][i + 1] = IntToHex(i * 16, 2);
		for (j = 0; j < 16; j++)
		{
			Source_StringGrid->Cells[j + 1][i + 1] = IntToHex(FRU_Data[i * 16 + j], 2);
			Reading_StringGrid->Cells[j + 1][i + 1] = TextBuf.sprintf("%c", FRU_Data[i * 16 + j]);
			//Reading_StringGrid->Cells[j+1][i+1]=IntToHex(255,2);
		}
	}

	for (i = 0; i < Name_Count; i++)
	{
//		Model_Name_Label0->Caption = Model_Name_Label0->Caption + TextBuf.sprintf("%c", FRU_Data[Name_Address + i]);
		Model_Name_Label1->Caption = Model_Name_Label1->Caption + TextBuf.sprintf("%c", FRU_Data[Name_Address + i]);
	}
	Model_Name_Label0->Caption = Application->Title.UpperCase();
    buf = "标签版本号是：" + RevStr + " 吗?";
    if (Application->MessageBoxA(buf.w_str(), L"提示", MB_YESNO|MB_ICONQUESTION) == IDNO)
	{
    	this->RevClick(Sender);
	}
	Rev_Label->Caption = RevStr;

	for (i = 0; i < Rev_Count; i++)
		FRU_Data[Rev_Address + i] = RevStr.c_str()[i];

	if (EEP_Mirror_Enable)
	{
		for (i = 0; i < Rev_Count; i++)
			FRU_Data[Rev_Address + i + 128] = RevStr.c_str()[i];
	}
	if (I2C_Interface_FLAG)
	{
		if (WriteOrRead)
		{
			FuncLabel->Font->Color = clPurple;
			FuncLabel->Caption = "Read Verify";
			Read_Verify->Visible = true;
			Write_Verify->Visible = false;
			ReadVerify->Checked = true;
			WriteVerify->Checked = false;
		}
		else
		{
			FuncLabel->Font->Color = clFuchsia;
			FuncLabel->Caption = "Write Verify";
			Read_Verify->Visible = false;
			Write_Verify->Visible = true;
			ReadVerify->Checked = false;
			WriteVerify->Checked = true;
		}
	}
	else
	{
		FuncLabel->Font->Color = clFuchsia;
		FuncLabel->Caption = "Write Verify";
		Read_Verify->Visible = false;
		Write_Verify->Visible = true;
		Write_Verify->Enabled = false;
		ReadVerify->Checked = false;
		WriteVerify->Checked = true;
	}
	Check_Data = false;
	FirstTime = true;
	Start_Time_Edit->Text = Now().FormatString("HH:MM:SS");
	End_Time_Edit->Text = Now().FormatString("HH:MM:SS");
    MainForm->StatusBar->Panels->Items[0]->Text = Fru_Model;
    MainForm->StatusBar->Panels->Items[3]->Text = "V1.04";
	MainForm->StatusBar->Panels->Items[4]->Text = Date_Compiled;
	hostIP = "";
#if RELEASE
	String sData = L"日志上传测试\r\n" + GetHostInfo() + Now().FormatString("yyyy-mm-dd HH:MM:SS");
	PMLogSave->FileName = L"9900000000000000000200XP002022010101010101.txt";
	PMLogSave->FileData = sData.BytesOf();
	try
	{
		PLogRet = SaveFileService->SaveAtRemoteFolder(PMLogSave);
		buf = PLogRet->SaveAtRemoteFolderResult;
	}
	catch (...)
	{
		buf = L"网络异常！";
	}

	if (buf != "ok")
	{
		Application->MessageBoxA(buf.w_str(), L"Error", IDOK | MB_ICONWARNING);
		buf = this->Caption + L"日志上传测试：" + buf;
		mniUploadLog->Checked = false;
	}
	else
	{
		GetIP *ip = new GetIP();
		GetIPResponse *pRe = SaveFileService->GetIP(ip);
		hostIP = pRe->GetIPResult;
		delete ip;
		buf = MainForm->Caption + hostIP + " 日志上传测试OK " + Now().FormatString("hh:nn:ss");
	}

	MainForm->Caption = buf;
#endif
}
//---------------------------------------------------------------------------
bool __fastcall CheckEEPBeforClr()
{
	bool pass = true;
	bool NotZero = false;
	int Dev_Add = SlaveAddress;
	int w_cmd = 0xE0;
	int r_cmd = 0xEl;
	int W_data[25] = {0};
	int R_data[25] = {0};
	int CRC8[20] = {0};
	int pec = 0;
	int i = 0;
	bool clr_pass = true;

	if (!I2C_Interface_FLAG)
	{
		return false;
	}

	W_data[0] = 0x14;
	W_data[1] = 0x20;
	CRC8[0] = Dev_Add;
	CRC8[1] = w_cmd;
	CRC8[2] = W_data[0];
	CRC8[3] = W_data[1];
	pec = calCRC8(CRC8, 4);
	W_data[2] = pec;

	//clear status information
	// GY7601_Write_Data(Dev_Add,w_cmd,3,W_data);
	Sleep(100);
	//  Gy7601_Read_Data(Dev_Add,w_cmd,3,R_data);
	Sleep(100);

	if (R_data[0] != 0x14 || R_data[1] != 0x20)
	{
		pass = false;
		return false;
	}
	r_cmd = 0xEl;
	//	Gy7601_Read_Data(Dev_Add,0xE1,16,R_data);

	for (i = 1; i < 16; i++)
	{
		if (R_data[i] != 0)
		{
			NotZero = true;
		}
	}
	if (NotZero == false)
	{
		ShowMessage("Black Box Operation Step 1 !\nRead E1h's data is Invalid !\nThe EEprom does not have any data !!!");
	}
	pass &= NotZero;

	return pass;
}
bool __fastcall CheckEEPAfterClr()
{
	bool pass = true;
	bool NotZero = true;
	int Dev_Add = SlaveAddress;
	int w_cmd = 0xE0;
	int r_cmd = 0xE1;
	int W_data[5] = {0};
	int R_data[25] = {0};
	int CRC8[20] = {0};
	int pec = 0;
	int i = 0;
	bool clr_pass = true;

	if (!I2C_Interface_FLAG)
	{
		return false;
	}
	W_data[0] = 0x14;
	W_data[1] = 0x20;
	CRC8[0] = Dev_Add;
	CRC8[1] = w_cmd;
	CRC8[2] = W_data[0];
	CRC8[3] = W_data[1];
	pec = calCRC8(CRC8, 4);
	W_data[2] = pec;

	//clear status information
	Sleep(100);
	// GY7601_Write_Data(Dev_Add,w_cmd,3,W_data);
	Sleep(200);
	// Gy7601_Read_Data(Dev_Add,w_cmd,3,R_data);
	Sleep(100);

	if (R_data[0] != 0x14 || R_data[1] != 0x20)
	{
		pass = false;
		return false;
	}
	//	Gy7601_Read_Data(Dev_Add,r_cmd,16,R_data);

	for (i = 1; i < 16; i++)
	{
		if (R_data[i] != 0)
		{
			NotZero = false;
			ShowMessage("Black Box Operation Step 3!\n Read E1h's Data are not All 0 !\nThe EEProm has not been Cleared!!!");
			break;
		}
	}
	pass &= NotZero;

	W_data[0] = 0x14;
	W_data[1] = 0x10; //change the location of the clear
	CRC8[0] = Dev_Add;
	CRC8[1] = w_cmd;
	CRC8[2] = W_data[0];
	CRC8[3] = W_data[1];
	pec = calCRC8(CRC8, 4);
	W_data[2] = pec;

	//clear status information
	Sleep(100);
	// GY7601_Write_Data(Dev_Add,w_cmd,3,W_data);
	Sleep(200);
	// Gy7601_Read_Data(Dev_Add,w_cmd,3,R_data);
	Sleep(100);

	if (R_data[0] != 0x14 || R_data[1] != 0x10)
	{
		pass = false;
		return false;
	}
	//	Gy7601_Read_Data(Dev_Add,r_cmd,16,R_data);

	for (i = 1; i < 16; i++)
	{
		if (R_data[i] != 0)
		{
			NotZero = false;
			return false;
		}
	}
	pass &= NotZero;

	return pass;
}
bool __fastcall ClrBBox(void)
{
#if CLR_BLACK_BOX
	int Dev_Add = SlaveAddress;
	int clrcmd = 0xE7;
	int W_data[5] = {0};
	int R_data[5] = {0};
	int CRC8[20] = {0};
	int pec = 0;
	bool clr_pass = true;

	if (!I2C_Interface_FLAG)
	{
		return false;
	}

	if (!CheckEEPBeforClr())
	{
		return false;
	}

	W_data[0] = 0x55;
	W_data[1] = 0xAA;
	CRC8[0] = Dev_Add;
	CRC8[1] = clrcmd;
	CRC8[2] = W_data[0];
	CRC8[3] = W_data[1];
	pec = calCRC8(CRC8, 4);
	W_data[2] = pec;

	//clear status information
	// GY7601_Write_Data(Dev_Add,clrcmd,3,W_data);
	Sleep(500);
	//  Gy7601_Read_Data(Dev_Add,clrcmd,2,R_data);
	Sleep(100);
	//	GY7601_Write_Data(Dev_Add,clrcmd,3,W_data);
	// Sleep(500);
	// Gy7601_Read_Data(Dev_Add,clrcmd,2,R_data);

	if (R_data[0] != 01)
	{
		clr_pass = clr_pass & false;
		ShowMessage("Clear Black Box Check Fail");
		return clr_pass;
	}

	W_data[0] = 0xAA;
	W_data[1] = 0x55;
	CRC8[0] = Dev_Add;
	CRC8[1] = clrcmd;
	CRC8[2] = W_data[0];
	CRC8[3] = W_data[1];
	pec = calCRC8(CRC8, 4);
	W_data[2] = pec;
	GY7601_Write_Data(Dev_Add, clrcmd, 3, W_data);
	Sleep(500);
	Gy7601_Read_Data(Dev_Add, clrcmd, 2, R_data);
	Sleep(100);
	GY7601_Write_Data(Dev_Add, clrcmd, 3, W_data);
	Sleep(500);
	Gy7601_Read_Data(Dev_Add, clrcmd, 2, R_data);

	if (R_data[0] != 02)
	{
		clr_pass = clr_pass & false;
		ShowMessage("Clear Black Box Check Fail");
	}
	if (!CheckEEPAfterClr())
	{
		return false;
	}
	// if(clr_pass==false)
	// {
	////	  ShowMessage("Clear Black Box Check Fail");
	//}
	//  ShowMessage("Pass");
	return clr_pass;
#else
	return true;
#endif
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::Write_VerifyClick(TObject *Sender)
{
	int ScanOK;
	byte w_data[10] = {0};
	byte r_data[10] = {0};
	int i, j;
	long int gt;
	time_t tnow;
	time_t t1;
	String infor[] = {"Test", "test"};
	String StationCode, msg, strTips, buf, sSn;
	time_t rawtime;
	BYTE buff[30] = {0};
	struct tm *target_time;
	tnow = time(NULL);
	Write_Verify->Enabled = false;
	Read_Verify->Enabled = false;
	Exit_Button->Enabled = false;
	Continue = true;
	bool bStationOK = false, bUpload = true;
	IpcMes->sSttion = L"I036-IPC条码信息写入";

	if (FirstTime)
	{
    	//如果要注释，需要Label_Check_Result = true(初始化）
		TCheck_Item_Form *form = new TCheck_Item_Form(this);
		form->ShowModal();
		delete form;
		if (Label_Check_Result)
		{
			FirstTime = false;
		}
		else
		{
			Exit_Button->Enabled = true;
			return;
		}
	}

	do
	{
		I2C_Interface_FLAG = true;
		if (I2C_Interface == "GY7601")
		{
			infor[0] = Com_port;
			I2C_DRV->Init_I2C_Bus(I2C_Interface, infor);
		}
		else if (I2C_Interface == "NI8451")
		{
			infor[0] = "0x" + IntToHex(SlaveAddress, 2);
		}
		else
		{
			I2C_DRV->Init_I2C_Bus(I2C_Interface, infor);
		}

		I2C_DRV->Init_I2C_Bus(I2C_Interface, infor);
		Check_Data = false;
		ProgressBar1->Min = 0;
		ProgressBar1->Max = 32;
		ProgressBar1->Position = 0;
		Check_Result = true;
		ScanOK = ScanBarCode('W');

		if (1 == ScanOK)
		{
			for (i = 0; i < 16; i++)
			{
				for (j = 0; j < 16; j++)
					Source_StringGrid->Cells[j + 1][i + 1] = IntToHex(FRU_Data[i * 16 + j], 2);
			}
			Status_Label->Caption = "CANCEL";
			Status_Label->Font->Color = clBlue;
			Check_Data = true;
			Reading_StringGrid->Refresh();
			goto End;
		}
		else
		{
			if (FirstTime)
			{
				if (IpcMes->bMesIsEnabed)
				{
					buf = Get99ModelNumber(Barcode_Label->Caption);
                    Bom99 = buf;
//					if (Bom99 != buf)
//					{
//						msg.sprintf(L"Bom料号不匹配! \n条码:%s; \n软件:%s", buf, Bom99);
//						Application->MessageBoxA(msg.w_str(), L"提示", MB_OK | MB_ICONSTOP);
//					}
				}
				FirstTime = false;
			}
		}
		
		Start_Time_Edit->Text = Now().FormatString("HH:MM:SS");
		if (Save_Check_SN() && SNDuplicateWarning->Checked)
		{
			TSN_Check_Form *form = new TSN_Check_Form(this);
			form->ShowModal();
			delete form;
		}

		if (Continue)
		{
			if (TimeSupport)
			{
				time(&rawtime);
				target_time = localtime(&rawtime);	// ㄤウ??
				target_time->tm_year = 1996 - 1900; //- 1900;
				target_time->tm_mon = 0;			// る - 1
				target_time->tm_mday = 1;			// ら
				target_time->tm_hour = 0;			// ?
				target_time->tm_min = 0;			// だ
				target_time->tm_sec = 0;			// ??
				t1 = mktime(target_time);

				gt = (tnow - t1) / 60;
				time_write = gt;
				FRU_Data[Time_No_Address] = gt & 0x0000FF;
				FRU_Data[Time_No_Address + 1] = (gt & 0x00FF00) >> 8;
				FRU_Data[Time_No_Address + 2] = (gt & 0xFF0000) >> 16;
			}
			/*
				FRU_Data[0x0B]=0XCE;
				FRU_Data[0x0C]=0XEB;
				FRU_Data[0x0D]=0X71;
			*/
			CheckSumFunc();

			Application->ProcessMessages();
			//  Sleep(50);
			for (i = 0; i < 16; i++)
			{
				for (j = 0; j < 16; j++)
					Source_StringGrid->Cells[j + 1][i + 1] = IntToHex(FRU_Data[i * 16 + j], 2);
			}
			/***************************************/

			if (EnableAspowerEepUnlock == true)
			{
				w_data[0] = 0xCC;
				w_data[1] = 0x11;
				I2C_DRV->PMBus_Block_Write(SlaveAddress, 2, w_data);
				Sleep(100);
				I2C_DRV->PMBus_Read_Byte(SlaveAddress, 0xE2, r_data);
				if (r_data[0] != 0x11)
				{
					ShowMessage("解锁写保护失败");
					Check_Result &= false;
				}
			}
			/***************************************/
			Write_FruData();
			///////////////////////////////////////////////////////////////////////////////////////////
			//begin to MfR /*//////////////////////////////////////////////////////////////////////////////////

			if (EnterTOFunc() == false)
			{
				ShowMessage("进入MFR模式失败！");
				Check_Result &= false;
			}

			WriteTOFunc(); //First Write data

            if(!VerifyFunc())
            {
              	WriteTOFunc();
                if(!VerifyFunc())
                {
                   ShowMessage("9E读取与写入不一致！");
                   Check_Result &= false;
                }
            }
			ExitTOFunc();
							  //exit
			/***************************************/ ///////////////////////////////////////////////////
			if (EnableAspowerEepUnlock == true)
			{
				w_data[0] = 0xCC;
				w_data[1] = 0x22;
				I2C_DRV->PMBus_Block_Write(SlaveAddress, 2, w_data);
				Sleep(100);
				I2C_DRV->PMBus_Read_Byte(SlaveAddress, 0xE2, r_data);
				if (r_data[0] != 0x22)
				{
					ShowMessage("加锁写保护失败");
					Check_Result &= false;
				}
			}
			/***************************************/
			Check_Data = true;
			Read_FruData();
			if (I2C_Interface != "GY7601")
				I2C_Interface_FLAG = I2C_DRV->I2C_bus;
			End_Time_Edit->Text = Now().FormatString("HH:MM:SS");

            msg = "";
            if (IpcMes->bMesIsEnabed)
            {
            	bUpload = true;
            	bStationOK = IpcMes->IpcMes_CheckSNStation(Barcode_Label->Caption);
                if (bStationOK == false)
                {
                	int nStart = IpcMes->sReturnStr.Pos("当前站");
                    int nEnd = IpcMes->sReturnStr.Pos("下一站");
                    if (nStart > 0)
                    {
                    	StationCode = IpcMes->sReturnStr.SubString(nStart + 4, 4);
                        msg = IpcMes->sReturnStr.SubString(nStart + 4, nEnd - nStart - 4);
                        if (StationCode == L"I035" || StationCode == L"I041")   //写入过站
                        {
                        	if(IsPacked(Barcode_Label->Caption))   //已装箱
                            {
                            	msg.sprintf(L"%s 已装箱，此为重码产品，请立即上报拉长处理！！！", Barcode_Label->Caption);
                                Check_Result = false;
                            }
                            else
                            {
                                msg.sprintf(L"过站警告！！%s 应为：%s", Barcode_Label->Caption, msg);
                            }
                            //上传数据
                        }
                        else
                        {
                            msg.sprintf(L"欠站警告！！%s 应为 %s", Barcode_Label->Caption, msg);
                            bUpload = false;
                        }
                    }
                    else
                    {
                     	msg = IpcMes->sReturnStr;
                        bUpload = false;
                    }
                }
            }
            if (msg.Length() > 3)
			{
				Application->MessageBoxA(msg.w_str(), L"MES Error", IDOK|MB_ICONSTOP);
			}

			if (Check_Result && I2C_Interface_FLAG)
			{
				Status_Label->Caption = "PASS";
				Status_Label->Font->Color = clGreen;
#if CSV_FILE_GENERATE
				for (i = 0; i < SN_Count; i++)
				{
					buff[i] = FRU_Data[SN_Address + i];
				}
				char *cSN = buff;
				sSn = cSN;
				SaveSnInforToCsv(sSn, "W");
#endif
			}
			else
			{
				Status_Label->Caption = "FAIL";
				Status_Label->Font->Color = clRed;
#if 0
				for (i=0; i<SN_Count; i++)
				{
		  			buff[i] = FRU_Data[SN_Address + i];
				}
		 		char *cSN = buff;
		 		sSn = cSN;
				SaveSnInforToCsv(sSn, "W");
#endif
			}
			Reading_StringGrid->Refresh();

			if (I2C_Interface_FLAG)
			{
				//if ((PASS_TXT->Checked && Check_Result) || (FAIL_TXT->Checked && !Check_Result) || All_TXT->Checked)
				Save_TXTData("WRITE", msg);
				if ((PASS_HEX->Checked && Check_Result) || (FAIL_HEX->Checked && !Check_Result) || All_HEX->Checked)
					Save_HEXData("WRITE");
				if ((PASS_BIN->Checked && Check_Result) || (FAIL_BIN->Checked && !Check_Result) || All_BIN->Checked)
					Save_BINData("WRITE");
			}

			if (IpcMes->bMesIsEnabed == true)
			{
				if (Check_Result == true)
				{
					IpcMes->sStationReslt = "PASS";
					IpcMes->sTestReslt = "Y";
					if (bUpload)
					{
						if (IpcMes->IpcMes_CheckUploadFruData(FRU_Data, 256, "IPC-W") == false)
						{
							ShowMessage(IpcMes->sReturnStr);
						}
					}
				}
				else
				{
					IpcMes->sStationReslt = "FAIL";
					IpcMes->sTestReslt = "N";
					if (bUpload)
					{
                    	if (IpcMes->IpcMes_CheckUploadFruData(FRU_Data, 256, "IPC-W") == false)
                        {
                            ShowMessage(IpcMes->sReturnStr);
                        }
                    }
				}
			}
		}
	} while (I2C_Interface_FLAG);
End:
	ProgressBar1->Position = ProgressBar1->Max;
	Write_Verify->Enabled = true;
	Read_Verify->Enabled = true;
	Write_Verify->SetFocus();
	Exit_Button->Enabled = true;
}
//-------------------------------Write_Func--------------------9*9999999999------------------------
bool __fastcall EnterTOFunc()
{
	//ShowMessage(3);
	byte u8WriteBufferArray[10] = {0};
	byte u8ReadBufferArray[10] = {0};
//	u8WriteBufferArray[0] = 0x2D;
//	u8WriteBufferArray[1] = 0x04;
//	u8WriteBufferArray[2] = 0x46;
//	u8WriteBufferArray[3] = 0x72;
//	u8WriteBufferArray[4] = 0x75;
//	u8WriteBufferArray[5] = 0x57;

	u8WriteBufferArray[0] = 0xF0;
	u8WriteBufferArray[1] = 0x43;
	u8WriteBufferArray[2] = 0x41;
	I2C_DRV->PMBus_Block_Write(SlaveAddress, 3, u8WriteBufferArray);
    Sleep(100);
	u8WriteBufferArray[0] = 0xEF;
	u8WriteBufferArray[1] = 0x02;
	u8WriteBufferArray[2] = 0x03;
    u8WriteBufferArray[3] = 0xC0;
    I2C_DRV->PMBus_Block_Write_Block_Read(SlaveAddress, 4, u8WriteBufferArray, 3, u8ReadBufferArray);

    u8WriteBufferArray[3] = 0xC1;
    I2C_DRV->PMBus_Block_Write_Block_Read(SlaveAddress, 4, u8WriteBufferArray, 3, u8ReadBufferArray);

    //I2C_DRV->PMBus_Block_Write(SlaveAddress, 4, u8WriteBufferArray);

//	I2C_DRV->PMBus_Read_Byte(SlaveAddress, 0x9C, u8ReadBufferArray);
//	if (u8ReadBufferArray[0] & 0x10 == 0)
//	{
//		return false;
//	}
//	else
//	{
//		return true;
//	}
}

bool __fastcall ExitTOFunc()
{
	byte u8WriteBufferArray[10] = {0};
	byte u8ReadBufferArray[10] = {0};
	u8WriteBufferArray[0] = 0x2D;
	u8WriteBufferArray[1] = 0x04;
	u8WriteBufferArray[2] = 0x57;
	u8WriteBufferArray[3] = 0x57;
	u8WriteBufferArray[4] = 0x57;
	u8WriteBufferArray[5] = 0x57;
	I2C_DRV->PMBus_Block_Write(SlaveAddress, 6, u8WriteBufferArray);
	I2C_DRV->PMBus_Read_Byte(SlaveAddress, 0x9C, u8ReadBufferArray);
	if (u8ReadBufferArray[0] & 0x10 == 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

void __fastcall WriteTOFunc()
{
	BYTE R_Data[20] = {0};
	int startAdd = 0x3A0;
    for(int i=0; i<14; i++)
    {
    	Check_Result &= Cali_WriteEep(SlaveAddress, startAdd, Write_sn[i]);
        startAdd++;
        Sleep(20);
    }
}

bool __fastcall Cali_WriteEep(BYTE salve, int add, BYTE Value)
{

	bool pass = true;
	AnsiString msg = "";
	BYTE w_data[20] = {0};
	BYTE r_data = 0;
	w_data[0] = 0xED;
	w_data[1] = HIBYTE(add);
	w_data[2] = LOBYTE(add);
	w_data[3] = Value;
	I2C_DRV->PMBus_Block_Write(salve, 4, w_data);
	Sleep(15);
    r_data = Cali_ReadEep(salve, add);
	if (r_data != Value)
	{
        msg = "9E写入的数据: " + IntToStr(Value);
        msg += " 读取的数据: ";
        msg += IntToStr(r_data);
		ShowMessage(msg);
		pass &= false;
	}
	return pass;
}

BYTE __fastcall Cali_ReadEep(BYTE add, WORD ptr)
{
	BYTE u8Data = 0;
	BYTE w_data[20] = {0};
	BYTE r_data[20] = {0};
	w_data[0] = 0xEF;
	w_data[1] = 0x02;
	w_data[2] = HIBYTE(ptr);
	w_data[3] = LOBYTE(ptr);
	I2C_DRV->PMBus_Block_Write_Block_Read(add, 4, w_data, 3, r_data);
	u8Data = r_data[1];
	return u8Data;
}

// Verify 9EFunc
bool __fastcall VerifyFunc()
{
	int i;
	bool yes1 = true;

	I2C_DRV->PMBus_Block_Read(SlaveAddress, 0x9E, 14, u8ReadBufferArray2);

	for (i = 0; i < 14; i++)
	{
		if (Write_sn[i] != u8ReadBufferArray2[i+1])
		{
			yes1 &= false;
		}
	}

	return yes1;
}

//---------------------------------------------------------------------------
void __fastcall TMainForm::Exit_ButtonClick(TObject *Sender)
{
	Close();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FormDestroy(TObject *Sender)
{
	mniUploadLog->Checked = true;
	FileSetAttr(ExtractFilePath(Application->ExeName) + Fru_Model, faArchive);
	Save_Ini_File(ExtractFilePath(Application->ExeName) + Fru_Model);
	FileSetAttr(ExtractFilePath(Application->ExeName) + Fru_Model, faReadOnly);
	if (I2C_Interface == "USB" && I2C_Interface_FLAG)
	{
		//Close_GY7601();
	}
#if RELEASE
	FileUpload();
#endif
}

bool __fastcall LockFunctionTest()
{
	bool bPass = false;
	byte Write_Buffer[2] = {0x55, 0xAA};
	byte Read_Buffer[2] = {0x00, 0x00};

	if (I2C_Interface_FLAG)
	{
#if _24LC064

		I2C_DRV->I2C_Write_24LC64(EEPROM_Address, 0x00, 2, Write_Buffer);
#else
		I2C_DRV->I2C_Write_24LC02(EEPROM_Address, 0x00, 2, Write_Buffer);
#endif

		Sleep(20);

#if _24LC064
		I2C_DRV->I2C_Read_24LC064(EEPROM_Address, 0x00, 2, Read_Buffer);

#else
		I2C_DRV->I2C_Read_24LC024(EEPROM_Address, 0x00, 2, Read_Buffer);
#endif
	}

	if ((Write_Buffer[0] == Read_Buffer[0]) && (Write_Buffer[1] == Read_Buffer[1]))
	{
		bPass = false;
	}
	else
	{
		bPass = true;
	}
	return bPass;
}

//---------------------------------------------------------------------------
void __fastcall Write_FruData()
{
	int i, j;
	BYTE Write_Data[16];

	for (i = 0; i < 16; i++)
	{
		if (I2C_Interface_FLAG)
		{
			MainForm->ProgressBar1->Position++;
			for (j = 0; j < 16; j++)
			{
				Write_Data[j] = FRU_Data[i * 16 + j];
			}

#if _24LC064
			//	GY7601_Write_24C64(EEPROM_Address,i*16,16,Write_Data);
			I2C_DRV->I2C_Write_24LC64(EEPROM_Address, i * 16, 16, Write_Data);
#else
			I2C_DRV->I2C_Write_24LC02(EEPROM_Address, i * 16, 16, Write_Data);
#endif

			Sleep(20);
		}
	}
}
//-----------------------------------------------------------------------------------
void __fastcall Read_FruData()
{
	int i, j;
	BYTE Read_Data[16];
	int MaskIndex = 0;
	bool Mask_En;
	for (i = 0; i < 16; i++)
	{
		MainForm->ProgressBar1->Position++;
		if (I2C_Interface_FLAG)
		{
			Sleep(20);
#if _24LC064
			I2C_DRV->I2C_Read_24LC064(EEPROM_Address, i * 16, 16, Read_Data);
			// Gy7601_Read_24C64(EEPROM_Address,i*16,16,Read_Data);
#else
			I2C_DRV->I2C_Read_24LC024(EEPROM_Address, i * 16, 16, Read_Data);
#endif

			for (j = 0; j < 16; j++)
			{
				Mask_En = false;
				if ((i * 16 + j) == MaskAddrTable[MaskIndex])
				{
					MaskIndex++;
					Mask_En = true;
					if (MaskIndex >= MaskAddrNum)
					{
						MaskIndex--;
						Mask_En = false;
					}
				}
				if (!Mask_En)
					if (FRU_Data[i * 16 + j] != Read_Data[j])
						Check_Result = Check_Result & false;
				MainForm->Reading_StringGrid->Cells[j + 1][i + 1] = IntToHex(Read_Data[j], 2);
			}
		}
	}
	Check_Result = Check_Result & ClrBBox();
}
//------------------------------------------------------------------------------------
void __fastcall TMainForm::Reading_StringGridDrawCell(TObject *Sender,
													  int ACol, int ARow, TRect &Rect, TGridDrawState State)
{
	if (ACol == 0 || ARow == 0)
		return;
	TColor bkcolor = clWindow;
	RECT R = Rect;
	UINT opt = 0;
	if (Check_Data)
	{
		if (Reading_StringGrid->Cells[ACol][ARow] != Source_StringGrid->Cells[ACol][ARow] ||
			Source_StringGrid->Cells[ACol][ARow] == 0xFF)
		{
			bkcolor = clRed;
		}
	}
	Reading_StringGrid->Canvas->Brush->Color = bkcolor;
	Reading_StringGrid->Canvas->FillRect(Rect);
	if (State.Contains(gdSelected))
	{
		Reading_StringGrid->Canvas->Brush->Color = clActiveCaption;
		Reading_StringGrid->Canvas->FillRect(Rect);
		Reading_StringGrid->Canvas->Brush->Style = bsClear;
		Reading_StringGrid->Canvas->Pen->Width = 2;
		Reading_StringGrid->Canvas->Pen->Color = clBlack;
		Reading_StringGrid->Canvas->Rectangle(R.left + 1, R.top + 1, R.right, R.bottom);
	}
	opt = DT_CENTER | DT_VCENTER | DT_SINGLELINE;
	DrawText(Reading_StringGrid->Canvas->Handle, Reading_StringGrid->Cells[ACol][ARow].t_str(), -1, &R, opt);
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Reading_StringGridClick(TObject *Sender)
{
	Source_StringGrid->Selection = Reading_StringGrid->Selection;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Source_StringGridClick(TObject *Sender)
{
	Reading_StringGrid->Selection = Source_StringGrid->Selection;
}
//---------------------------------------------------------------------------
int __fastcall ScanBarCode(char rw)
{
	int i;
	bool PN_Check;
	bool Snflag = false;
	String ScanBarCode, strTips;
	char *SN, *PN;
	bool MesSnCheckFlag = true;
    int len=0;
	if (PNSupport)
	{
		do
		{
			ScanBarCode = "";
			PN_Check = true;
			if (rw == 'r' || rw == 'R')
			{
				if (!InputQuery(L"请输入PN码", L"Scan PN BarCode Label", ScanBarCode))
					return 1;
			}
			else if (rw == 'w' || rw == 'W')
			{
				if (!InputQuery(L"请输入PN码", L"Scan PN BarCode Label", ScanBarCode))
					return 1;
			}
			else
				return 1;
			ScanBarCode = UpperCase(ScanBarCode);
			PN = ScanBarCode.t_str();
			if (ScanBarCode.Length() != Model_No_Count)
			{	//if(ScanBarCode.Length()!=22)
				//PN_Check = PN_Check&false;
				//else
				// = true  ;
			}
			if (Snflag == false)
			{
				for (i = 0; i < Model_No_Count; i++)
				{
					if (PN[i] != FRU_Data[Model_No_Address + i])
						PN_Check = PN_Check & false;
				}
			}
			else
			{
				for (i = 0; i < Model_No_Count - 8; i++)
				{
					if (PN[i] != FRU_Data[Model_No_Address + i])
						PN_Check = PN_Check & false;
				}
				for (i = Model_No_Count - 8; i < Model_No_Count; i++)
				{
					if (PN[i] != 0x20)
						PN_Check = PN_Check & false;
				}
			}

			if (!PN_Check)
				ShowMessage("PN Barcode label error??");
			//useless
//			for (int j = 0; j < Name_Count; j++)
//			{
//
//				Write_pn[j + 2] = FRU_Data[Model_No_Address + j];
//			}
		} while (!PN_Check);
	}

	do
	{
		ScanBarCode = "";
		if (rw == 'r' || rw == 'R')
		{
			if (!InputQuery("请输入SN码", "Scan SN BarCode Label", ScanBarCode))
				return 1;
		}
		else if (rw == 'w' || rw == 'W')
		{
			if (!InputQuery("请输入SN码", "Scan SN BarCode Label", ScanBarCode))
				return 1;
		}
		else
			return 1;
		ScanBarCode = UpperCase(ScanBarCode);
        len =  ScanBarCode.Length();
		if ( len!= 14)
			ShowMessage("Barcode label error??");
        SN = ScanBarCode.t_str();
		if (IpcMes->bMesIsEnabed == true)
		{

			//MesSnCheckFlag = IpcMes->IpcMes_CheckSNStattion(SN);
			if (MesSnCheckFlag == false)
			{
				ShowMessage(IpcMes->sReturnStr);
			}
		}
	} while (len != 14 || MesSnCheckFlag == false);

	MainForm->Status_Label->Caption = "";
	MainForm->Barcode_Label->Caption = SN;
	Sleep(300);
	Application->ProcessMessages();
	//get FRM data  begin
	for (i = 0; i < 14; i++)
	{

		Write_sn[i] = SN[i];
		FRU_Data[SN_Address + i] = SN[i];
		//	 FRU_Data[Mfr_Sn_Address+i]=SN[i];
	}
//	for (int j = 0; j < Name_Count; j++)
//	{
//		Write_pn[j + 2] = FRU_Data[Model_No_Address + j];
//	}
	//get FRM data end
	//  Date_Calc(ScanBarCode);
	//	FRU_Data[Mfr_Sn_Address+i-1]=0x20;;
	//	FRU_Data[SN_Address+i-1]=0X20;

	if (EEP_Mirror_Enable == true)
	{
		for (i = 0; i < 128; i++)
		{

			FRU_Data[i + 128] = FRU_Data[i];
		}
	}
	return 0;
}
void __fastcall Date_Calc(String str)
{ //PSF917H1001A
	/*
//PS  ---power supply
  F   2---Year +2010 = 2016
  9   3---Month 0-C
  17  4,5---Day  0-31
  H
  1001A
  */

	// int date[10]
	int data[10] = {0};
	int year1 = 0;
	int year2 = 0;
	int month1 = 0;
	int month2 = 0;
	int day1 = 0;
	int day2 = 0;
	int buff = 0;
	int tmp[20] = {0};
	AnsiString s = str;
	char *str1 = str.t_str();

	int i = 0;
	time_t t = time(0);
	for (i = 0; i < str.Length(); i++)
	{
		tmp[i] = str1[i]; //str.SubString(1+i,1);
	}
	//year
	data[0] = '2';
	data[1] = '0';

	data[6] = tmp[4];
	data[7] = tmp[5];

	if (tmp[2] > 'O')
	{
		tmp[2] -= 2;
	}
	else if (tmp[2] > 'I')
	{
		tmp[2] -= 1;
	}
	else
	{
	}

	buff = 10 + tmp[2] - 65;	//
	data[3] = buff % 10 + 0x30; //1
	data[2] = buff / 10 + 0x30; //6

	//Month
	if (tmp[3] >= 65)
	{
		tmp[3] = tmp[3] - 65 + 10;
	}
	else
	{
		tmp[3] = tmp[3] - 0x30;
	}
	//month2 = tmp[3]%10;
	// data[4]=
	data[5] = tmp[3] % 10 + 0x30;
	data[4] = (tmp[3] / 10) + 0x30;
	data[6] = tmp[4];
	data[7] = tmp[5];
	for (i = 0; i < Mfr_Date_Count; i++)
	{
		FRU_Data[Mfr_Date_Address + i] = data[i];
		//int Mfr_Date_Count=8;Mfr_Date_Address=0x57;
	}
}
//------------------------------------------------------------------------------------------
void __fastcall CheckSumFunc(void)
{
	unsigned int Sum;
	int i;

	Sum = 0;
	for (i = Chksum1_Begin; i <= Chksum1_End; i++)
	{
		Sum = Sum + FRU_Data[i];
	}
	FRU_Data[Chksum1_Loct] = (0x100 - (Sum & 0x00FF)) & 0x00FF;
	//FRU_Data[0xff]=FRU_Data[Chksum1_Loct];
}
//---------------------------------------------------------------------------------
void __fastcall TMainForm::Read_VerifyClick(TObject *Sender)
{
	int ScanOK, i, j;
	BYTE Read_Data[255];
	long int gt;
	BYTE buff[30] = {0};
	String infor[5] = {"1", "2"};
	String strTips, StationCode, buf, msg;
	Write_Verify->Enabled = false;
	Read_Verify->Enabled = false;
	Exit_Button->Enabled = false;
    bool bStationOK = false, bUpload = true;
	Continue = true;

	IpcMes->sSttion = L"I037-IPC条码信息验证";

	if (FirstTime)
	{
	    //如果要注释，需要Label_Check_Result = true(初始化）
		TCheck_Item_Form *form = new TCheck_Item_Form(this);
		form->ShowModal();
		delete form;
		if (Label_Check_Result)
			FirstTime = false;
		else
		{
			Exit_Button->Enabled = true;
			return;
		}
	}

	do
	{
		I2C_Interface_FLAG = true;
		if (I2C_Interface == "GY7601")
		{
			infor[0] = Com_port;
			I2C_DRV->Init_I2C_Bus(I2C_Interface, infor);
		}
		else if (I2C_Interface == "NI8451")
		{
			infor[0] = "0x" + IntToHex(SlaveAddress, 2);
		}
		else
		{
			I2C_DRV->Init_I2C_Bus(I2C_Interface, infor);
		}

		I2C_DRV->Init_I2C_Bus(I2C_Interface, infor);
		Check_Data = false;
		Check_Result = true;
		ProgressBar1->Min = 0;
		ProgressBar1->Max = 16;
		ProgressBar1->Position = 0;
		ScanOK = ScanBarCode('R');

		if (1 == ScanOK)
		{
			for (i = 0; i < 16; i++)
			{
				for (j = 0; j < 16; j++)
					Source_StringGrid->Cells[j + 1][i + 1] = IntToHex(FRU_Data[i * 16 + j], 2);
			}
			Status_Label->Caption = "CANCEL";
			Status_Label->Font->Color = clBlue;
			Check_Data = true;
			Reading_StringGrid->Refresh();
			goto End;
		}
		else
		{
			if (FirstTime)
			{
				if (IpcMes->bMesIsEnabed)
				{
					buf = Get99ModelNumber(Barcode_Label->Caption);
                    Bom99 = buf;
//					if (Bom99 != buf)
//					{
//						msg.sprintf(L"Bom料号不匹配！\n条码：%s;\n软件：%s", buf, Bom99);
//						Application->MessageBoxA(msg.w_str(), L"提示", MB_OK | MB_ICONSTOP);
//					}
				}
				FirstTime = false;
			}
		}
		
		Start_Time_Edit->Text = Now().FormatString("HH:MM:SS");
		if (Save_Check_SN() && SNDuplicateWarning->Checked)
		{
			TSN_Check_Form *form = new TSN_Check_Form(this);
			form->ShowModal();
			delete form;
		}
		if (Continue)
		{
			if (TimeSupport)
			{
				CheckTimeFunc();

#if _24LC064
				I2C_DRV->I2C_Read_24LC064(EEPROM_Address, i * 16, 16, Read_Data);
				//  Gy7601_Read_24C64(EEPROM_Address,i*16,16,Read_Data);
#else
				I2C_DRV->I2C_Read_24LC024(EEPROM_Address, i * 16, 16, Read_Data);
#endif
				FRU_Data[Time_No_Address] = Read_Data[0];
				FRU_Data[Time_No_Address + 1] = Read_Data[1];
				FRU_Data[Time_No_Address + 2] = Read_Data[2];
			}
			CheckSumFunc();
			for (i = 0; i < 16; i++)
			{
				for (j = 0; j < 16; j++)
					Source_StringGrid->Cells[j + 1][i + 1] = IntToHex(FRU_Data[i * 16 + j], 2);
			}
			Check_Data = true;
			Read_FruData();
			if (EnterTOFunc() == false)
			{
				ShowMessage("进入MFR模式失败！");
				Check_Result &= false;
			}

            if(!VerifyFunc())
            {
              	WriteTOFunc();
                if(!VerifyFunc())
                {
                   ShowMessage("9E读取与写入不一致！");
                   Check_Result &= false;
                }
            }
			ExitTOFunc();
			Application->ProcessMessages();
			End_Time_Edit->Text = Now().FormatString("HH:MM:SS");
            msg = "";
            if (IpcMes->bMesIsEnabed)
            {
            	bUpload = true;
            	bStationOK = IpcMes->IpcMes_CheckSNStation(Barcode_Label->Caption);
                if (bStationOK == false)
                {
                	int nStart = IpcMes->sReturnStr.Pos("当前站");
                    int nEnd = IpcMes->sReturnStr.Pos("下一站");
                    if (nStart > 0)
                    {
                    	StationCode = IpcMes->sReturnStr.SubString(nStart+4, 4);
                        msg = IpcMes->sReturnStr.SubString(nStart + 4, nEnd - nStart - 4);
                        if (StationCode == L"I035" || StationCode == L"I041")   //读取过站
                        {
                        	if(IsPacked(Barcode_Label->Caption))   //已装箱
                            {
                            	msg.sprintf(L"%s 已装箱，此为重码产品，请立即上报拉长处理！！！", Barcode_Label->Caption);
                                Check_Result = false;
                            }
                            else
                            {
                                msg.sprintf(L"过站警告！！%s 应为：%s", Barcode_Label->Caption, msg);
                            }
                            //上传数据
                        }
                        else
                        {
                            msg.sprintf(L"欠站警告！！%s 应为 %s", Barcode_Label->Caption, msg);
                            Check_Result = false;
                            bUpload = false;
                        }
                    }
                    else
                    {
                     	msg = IpcMes->sReturnStr;
                        bUpload = false;
                    }
                }
            }
            if (msg.Length() > 3)
			{
				Application->MessageBoxA(msg.w_str(), L"MES Error", IDOK | MB_ICONSTOP);
			}

            if (Mark2B != L"00")
            {
            	Check_Result &= Read2B(buf);
				strLog += buf;
            }
			if (Check_Result)
			{
				Status_Label->Caption = "PASS";
				Status_Label->Font->Color = clGreen;

#if CSV_FILE_GENERATE
				for (i = 0; i < SN_Count; i++)
				{
					buff[i] = FRU_Data[SN_Address + i];
				}
				char *cSN = buff;
				String sSn = cSN;
				SaveSnInforToCsv(sSn, "R");
#endif
			}
			else
			{
				Status_Label->Caption = "FAIL";
				Status_Label->Font->Color = clRed;
#if 0
				for(i = 0; i < SN_Count; i++)
				{
		  			buff[i] = FRU_Data[SN_Address + i];
				}
		 		char *cSN = buff;
		 		String sSn = cSN;
				SaveSnInforToCsv(sSn, "R");
#endif
			}
			Reading_StringGrid->Refresh();

			if (I2C_Interface_FLAG)
			{
				//if ((PASS_TXT->Checked && Check_Result) || (FAIL_TXT->Checked && !Check_Result) || All_TXT->Checked)
				Save_TXTData("READ", msg);
				if ((PASS_HEX->Checked && Check_Result) || (FAIL_HEX->Checked && !Check_Result) || All_HEX->Checked)
					Save_HEXData("READ");
				if ((PASS_BIN->Checked && Check_Result) || (FAIL_BIN->Checked && !Check_Result) || All_BIN->Checked)
					Save_BINData("READ");
			}
			if (IpcMes->bMesIsEnabed)
			{
				if (Check_Result)
				{
					IpcMes->sStationReslt = "PASS";
					IpcMes->sTestReslt = "Y";
                    if (bUpload)
                    {
                        if (IpcMes->IpcMes_CheckUploadFruData(FRU_Data, 256, "IPC-R") == false)
                        {
                            ShowMessage(IpcMes->sReturnStr);
                        }
                    }
				}
				else
				{
					IpcMes->sStationReslt = "FAIL";
					IpcMes->sTestReslt = "N";
                    if (bUpload)
                    {
                    	if (IpcMes->IpcMes_CheckUploadFruData(FRU_Data, 256, "IPC-R") == false)
                        {
                            ShowMessage(IpcMes->sReturnStr);
                        }
                    }
				}
			}
		}
	} while (I2C_Interface_FLAG);
End:
	ProgressBar1->Position = ProgressBar1->Max;
	Write_Verify->Enabled = true;
	Read_Verify->Enabled = true;
	Read_Verify->SetFocus();
	Exit_Button->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall CheckTimeFunc(void)
{
	long int time_check;
	unsigned long int TimeDiff1, TimeDiff2, TimeTemp;
	BYTE Read_time[10], Time_Now[5];
	AnsiString str;
	time_t t1;
	time_t rawtime;
	struct tm *target_time;
	time_t tnow;
	tnow = time(NULL);

	time(&rawtime);
	target_time = localtime(&rawtime); // ㄤウ??
	target_time->tm_year = 1996 - 1900;
	target_time->tm_mon = 0;  // る - 1
	target_time->tm_mday = 1; // ら
	target_time->tm_hour = 0; // ?
	target_time->tm_min = 0;  // だ
	target_time->tm_sec = 0;  // ??
	t1 = mktime(target_time);

	TimeDiff1 = (tnow - t1) / 60;
	Time_Now[0] = TimeDiff1 & 0xff;
	Time_Now[1] = (TimeDiff1 & 0xff00) >> 8;
	Time_Now[2] = (TimeDiff1 & 0xff0000) >> 16;

#if _24LC064
	I2C_DRV->I2C_Read_24LC064(EEPROM_Address, (WORD)Time_No_Address, Time_No_Count, Read_time);
#else
	I2C_DRV->I2C_Read_24LC024(EEPROM_Address, Time_No_Address, Time_No_Count, Read_time);
#endif

	TimeDiff2 = (Read_time[0] + Read_time[1] * 256 + Read_time[2] * 65536);
	str = "Time Now :" + IntToHex(Time_Now[0], 2) + IntToHex(Time_Now[1], 2) + IntToHex(Time_Now[2], 2);
	str = str + "\nTime Write:" + IntToHex(Read_time[0], 2) + IntToHex(Read_time[1], 2) + IntToHex(Read_time[2], 2);

	// ShowMessage(str);
	if (TimeDiff1 > TimeDiff2)
	{
		TimeTemp = (TimeDiff1 - TimeDiff2) / 60;
		str = str + "\nTime Diff:" + IntToStr((INT)(TimeDiff1 - TimeDiff2)) + " min";
	}
	else
	{
		TimeTemp = (TimeDiff2 - TimeDiff1) / 60;
		str = str + "\nTime Diff:" + IntToStr((INT)(TimeDiff2 - TimeDiff1)) + " min";
	}

	if ((TimeTemp) >= 4)
	{
		ShowMessage("FAIL!!!    Please Regulate the Computer System time!");
		ShowMessage(str);
		Check_Result = False;
	}
}

void __fastcall Save_HEXData(AnsiString RW)
{
	FILE *Data_File;
	AnsiString Dir_Name, Hex_FileName;
	bool Data_Line_FF;
	int i, j, Csum, Recoder_Count;
	int No_Byte = 0x10;		//is the number of data bytes in the record.
	int Record_Type = 0x00; // is the record type 00 (a data record).
	Dir_Name = ExtractFilePath(Application->ExeName) + RW + "\\";
	if (!DirectoryExists(Dir_Name))
		CreateDir(Dir_Name);
	Dir_Name = Dir_Name + Now().FormatString("yyyymmdd") + "\\";
	if (!DirectoryExists(Dir_Name))
		CreateDir(Dir_Name);

	for (i = 1; i < 256; i++)
	{
		Recoder_Count = i;
		Hex_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
					   MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".Hex";
		if (FileExists(Hex_FileName))
		{
			DeleteFile(Hex_FileName);
			Recoder_Count = i + 1;
			Hex_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
						   MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".Hex";
			goto SaveHEXData;
		}
	}
SaveHEXData:
	if (Recoder_Count >= 255)
	{
		Recoder_Count = 1;
		Hex_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
					   MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".Hex";
	}

	Data_File = fopen(Hex_FileName.c_str(), "w");
	for (i = 0; i < 16; i++)
	{
		for (j = 0; j < 16; j++)
		{
			Data_Line_FF = true;
			//if(StrToInt("0x"+MainForm->Source_StringGrid->Cells[j+1][i+1])!=0xFF)
			if (StrToInt("0x" + MainForm->Reading_StringGrid->Cells[j + 1][i + 1]) != 0xFF)
				Data_Line_FF = Data_Line_FF & false;
		}
		if (!Data_Line_FF)
		{
			fprintf(Data_File, ":10%s", IntToHex(i * 16, 4).t_str());
			Csum = No_Byte + (((i * 16) & 0xFF00) / 256) + ((i * 16) & 0xFF) + Record_Type;
			for (j = 0; j < 16; j++)
			{
				//fprintf(Data_File,"%s",MainForm->Source_StringGrid->Cells[j+1][i+1]);
				//Csum=Csum+StrToInt("0x"+MainForm->Source_StringGrid->Cells[j+1][i+1]);
				fprintf(Data_File, "%s", MainForm->Reading_StringGrid->Cells[j + 1][i + 1]);
				Csum = Csum + StrToInt("0x" + MainForm->Reading_StringGrid->Cells[j + 1][i + 1]);
			}
			fprintf(Data_File, "%s\n", IntToHex((0x100 - (Csum & 0xFF)) & 0xFF, 2));
		}
	}
	fprintf(Data_File, ":00000001FF");
	fclose(Data_File);
}
//---------------------------------------------------------------------------

void __fastcall Save_TXTData(AnsiString RW, String msg)
{
	FILE *Data_File;
	AnsiString Dir_Name, Text_FileName, buf, buf1, buf2;
	byte u8Arr[20] = {0};
	String sBuf;
    bool bResult;
	int i, j, Recoder_Count;

	Dir_Name = ExtractFilePath(Application->ExeName) + RW + "\\";
	if (!DirectoryExists(Dir_Name))
		CreateDir(Dir_Name);
	Dir_Name = Dir_Name + Now().FormatString("yyyymmdd") + "\\";
	if (!DirectoryExists(Dir_Name))
		CreateDir(Dir_Name);

	for (i = 1; i < 256; i++)
	{
		Recoder_Count = i;
		Text_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
						MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".txt";
		if (FileExists(Text_FileName))
		{
			DeleteFile(Text_FileName);
			Recoder_Count = i + 1;
			Text_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
							MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".txt";
			goto SaveTXTData;
		}
	}
SaveTXTData:
	if (Recoder_Count >= 255)
	{
		Recoder_Count = 1;
		Text_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
						MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".txt";
	}
	Data_File = fopen(Text_FileName.c_str(), "w");
	sBuf = L"ces" + MainForm->Status_Label->Caption;
	if (sBuf.Length() > 4)
		buf = sBuf.SubString(sBuf.Length() - 3, 4);
	bResult = buf == "PASS";
	buf1 = GetFileHeader(MainForm->Barcode_Label->Caption, buf, Text_FileName);
	buf2 = msg;
	fprintf(Data_File, "%sMES提示：%s\n\n\n", buf1.c_str(), buf2.c_str());

	for (i = 0; i < 17; i++)
	{
		for (j = 0; j < 17; j++)
		{
			if (i == 0 && j == 0)
			{
				fprintf(Data_File, "   ");
			}
			else
			{
				buf = MainForm->Source_StringGrid->Cells[j][i];
				fprintf(Data_File, "%s ", buf.c_str());
			}
		}
		fprintf(Data_File, "\n");
	}

	fprintf(Data_File, "\n\n实际读取：\n\n");

    for (i = 0; i < 17; i++)
	{
    	for (j = 0; j < 17; j++)
		{
        	if (i != 0)
			{
				buf = MainForm->Reading_StringGrid->Cells[j][i];
				fprintf(Data_File, "%s ",buf.c_str());
			}
        }
        fprintf(Data_File, "\n");
    }

	fprintf(Data_File, "9E W:");

	//Barcode_Label
	fprintf(Data_File, MainForm->Barcode_Label->Caption.t_str());
	fprintf(Data_File, "\n");
	fprintf(Data_File, "9E R:");
	for (int b = 0; b < 14 + 2; b++)
	{
		fprintf(Data_File, (IntToHex(u8ReadBufferArray2[b], 2) + " ").t_str());
	}
	fprintf(Data_File, "\n");
	fprintf(Data_File, strLog.c_str());
	fclose(Data_File);
#if RELEASE
    buf = GetUploadFileName(MainForm->Barcode_Label->Caption, bResult);
    MainForm->mniUploadLog->Checked = CUploadLogService(buf, Text_FileName);
#endif
}

//---------------------------------------------------------------------------
bool __fastcall Save_Check_SN()
{
	FILE *Data_File;
	AnsiString Dir_Name, Text_FileName;
	int i, j, Recoder_Count;
	bool SN_The_Same = false;
	Dir_Name = ExtractFilePath(Application->ExeName) + "Check\\";
	if (!DirectoryExists(Dir_Name))
		CreateDir(Dir_Name);
	Dir_Name = Dir_Name + Now().FormatString("yyyymmdd") + "\\";
	if (!DirectoryExists(Dir_Name))
		CreateDir(Dir_Name);

	for (i = 1; i < 256; i++)
	{
		Recoder_Count = i;
		Text_FileName = Dir_Name + "Check_" + MainForm->Barcode_Label->Caption + "-" +
						MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".txt";
		if (FileExists(Text_FileName))
		{
			SN_The_Same = true;
			DeleteFile(Text_FileName);
			Recoder_Count = i + 1;
			Text_FileName = Dir_Name + "Check_" + MainForm->Barcode_Label->Caption + "-" +
							MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".txt";
			goto SaveSNData;
		}
	}
SaveSNData:
	if (Recoder_Count >= 255)
	{
		Recoder_Count = 1;
		Text_FileName = Dir_Name + "Check_" + MainForm->Barcode_Label->Caption + "-" +
						MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".txt";
	}
	Data_File = fopen(Text_FileName.c_str(), "w");
	fclose(Data_File);
	return SN_The_Same;
}
//---------------------------------------------------------------------------
void __fastcall Open_Ini_File(AnsiString FileName)
{
	AnsiString Read_Str_Buf;
	bool bRet;

	if (!FileExists(FileName))
	{
		ShowMessage(FileName + " 文件不存在");
	}
	else
	{
		TIniFile *IniFile = new TIniFile(FileName);

		EEPROM_Address = StrToInt("0x" + IniFile->ReadString("General", "P/S Address", "A0"));
		SlaveAddress = StrToInt("0x" + IniFile->ReadString("General", "Slave_Address", "B0"));
		Com_port = IniFile->ReadString("General", "COM_PORT", "COM10");
		I2C_Interface = IniFile->ReadString("General", "I2C_Interface", "USB");
		I2C_Frequency = IniFile->ReadInteger("General", "USBI2C_Frequency", 100);
		RevStr = IniFile->ReadString("General", "Rev", "00");
		WriteOrRead = IniFile->ReadInteger("General", "WriteOrRead", 0);
		MainForm->Model_Name_Label0->Caption = IniFile->ReadString(L"General", L"Model Name", L"U1A-XX");
		Read_Str_Buf = IniFile->ReadString("General", "Save TXT Data", "0");

		if (Read_Str_Buf == "0")
		{
			MainForm->TXT_Label->Caption = "Save TXT Data : None";
			MainForm->None_TXT->Checked = true;
		}
		else if (Read_Str_Buf == "1")
		{
			MainForm->TXT_Label->Caption = "Save TXT Data : PASS";
			MainForm->PASS_TXT->Checked = true;
		}
		else if (Read_Str_Buf == "2")
		{
			MainForm->TXT_Label->Caption = "Save TXT Data : FAIL";
			MainForm->FAIL_TXT->Checked = true;
		}
		else if (Read_Str_Buf == "3")
		{
			MainForm->TXT_Label->Caption = "Save TXT Data : All";
			MainForm->All_TXT->Checked = true;
		}

		Read_Str_Buf = IniFile->ReadString("General", "Save HEX Data", "0");
		if (Read_Str_Buf == "0")
		{
			MainForm->Hex_Label->Caption = "Save HEX Data : None";
			MainForm->None_HEX->Checked = true;
		}
		else if (Read_Str_Buf == "1")
		{
			MainForm->Hex_Label->Caption = "Save HEX Data : PASS";
			MainForm->PASS_HEX->Checked = true;
		}
		else if (Read_Str_Buf == "2")
		{
			MainForm->Hex_Label->Caption = "Save HEX Data : FAIL";
			MainForm->FAIL_HEX->Checked = true;
		}
		else if (Read_Str_Buf == "3")
		{
			MainForm->Hex_Label->Caption = "Save HEX Data : All";
			MainForm->All_HEX->Checked = true;
		}
		Read_Str_Buf = IniFile->ReadString("General", "Save BIN Data", "0");

		if (Read_Str_Buf == "0")
		{
			MainForm->BIN_Label->Caption = "Save BIN  Data : None";
			MainForm->None_BIN->Checked = true;
		}
		else if (Read_Str_Buf == "1")
		{
			MainForm->BIN_Label->Caption = "Save BIN  Data : PASS";
			MainForm->PASS_BIN->Checked = true;
		}
		else if (Read_Str_Buf == "2")
		{
			MainForm->BIN_Label->Caption = "Save BIN  Data : FAIL";
			MainForm->FAIL_BIN->Checked = true;
		}
		else if (Read_Str_Buf == "3")
		{
			MainForm->BIN_Label->Caption = "Save BIN  Data : All";
			MainForm->All_BIN->Checked = true;
		}

		bRet = IniFile->ReadBool("General", "SN Duplicate Warning", false);
	    MainForm->SNDuplicateWarning->Checked = bRet;
	    MainForm->SN_Dup_Label->Caption = bRet ? "重复提示开" : "重复提示关";

        PassWord_str = IniFile->ReadString("General", "Pass Word", "Fru_Test");
        Label_File_Name = IniFile->ReadString("General", "Label File Name", "Example.png");
        bRet = IniFile->ReadBool("General", "MesEnable", false);
        MainForm->ckiMesOffLine->Checked = IpcMes->bMesIsEnabed = bRet;
        MainForm->StatusBar->Panels->Items[2]->Text = bRet ? "MES Online" : "MES Offline";
        MainForm->Unlock->Checked = EnableAspowerEepUnlock = IniFile->ReadBool("General", "UnlockSupport", false);

	    MainForm->AutoExit1->Checked = bAutoExitFlag = IniFile->ReadBool("General", "AutoExitFlag",false);
	    Address_Enum = IniFile->ReadString("General", "Address_Enum", "A0/B0");
	    sTips = IniFile->ReadString("General", "Tips", "");
	    Bom99 = IniFile->ReadString("General", "BomNumber", "990000");
	    MainForm->htpr1->WSDLLocation = IniFile->ReadString("General", "LogServiceURL", "http://172.26.0.203:8011/ServiceSaveFile.asmx?wsdl");
        MainForm->mniGetBom2->Checked = IniFile->ReadBool("General", "GetBom2", false);
		Mark2B = IniFile->ReadString("General", "Mark2B", "00");

		delete IniFile;
	}
}
//--------------------------------------------------------------------------------------------
void __fastcall Save_Ini_File(AnsiString FileName)
{
	AnsiString IniStringBuf;
	bool bRet;

	if (!FileExists(FileName))
	{
		return;
	}
	TIniFile *IniFile = new TIniFile(FileName);

	IniFile->WriteString("General", "P/S Address", IntToHex(EEPROM_Address, 2));
	IniFile->WriteString("General", "Slave_Address", IntToHex(SlaveAddress, 2));

	IniFile->WriteString("General", "COM_PORT", Com_port);
	IniFile->WriteString("General", "I2C_Interface", I2C_Interface);
	IniFile->WriteInteger("General", "USBI2C_Frequency", I2C_Frequency);
	IniFile->WriteString("General", "Rev", RevStr);
	IniFile->WriteInteger("General", "WriteOrRead", WriteOrRead);
	if (MainForm->None_TXT->Checked == true)
		IniFile->WriteString("General", "Save TXT Data", "0");
	else if (MainForm->PASS_TXT->Checked == true)
		IniFile->WriteString("General", "Save TXT Data", "1");
	else if (MainForm->FAIL_TXT->Checked == true)
		IniFile->WriteString("General", "Save TXT Data", "2");
	else if (MainForm->All_TXT->Checked == true)
		IniFile->WriteString("General", "Save TXT Data", "3");
	if (MainForm->None_HEX->Checked == true)
		IniFile->WriteString("General", "Save HEX Data", "0");
	else if (MainForm->PASS_HEX->Checked == true)
		IniFile->WriteString("General", "Save HEX Data", "1");
	else if (MainForm->FAIL_HEX->Checked == true)
		IniFile->WriteString("General", "Save HEX Data", "2");
	else if (MainForm->All_HEX->Checked == true)
		IniFile->WriteString("General", "Save HEX Data", "3");

	IniFile->WriteString("General", "Label File Name", Label_File_Name);

    bRet = MainForm->SNDuplicateWarning->Checked;
    IniFile->WriteBool("General", "SN Duplicate Warning", bRet);

	IniFile->WriteBool("General", "MesEnable", IpcMes->bMesIsEnabed);
	IniFile->WriteBool("General", "UnlockSupport", EnableAspowerEepUnlock);
	IniFile->WriteBool("General", "AutoExitFlag", bAutoExitFlag);

	delete IniFile;
}
//-----------------------------------------------------------------------
void __fastcall TMainForm::About1Click(TObject *Sender)
{
	TAboutBox *AboutBox = new TAboutBox(this);
	AboutBox->ShowModal();
	delete AboutBox;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ISAClick(TObject *Sender)
{
	String info[3] = {"te", "te"};
	I2C_Interface = "GY7601";
	ISA->Checked = true;

	//I2C_DRV->Init_I2C_Bus(I2C_Interface, info);
	Initial_USB_Intreface();
	USBI2C_Freq->Enabled = false;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::USBClick(TObject *Sender)
{
	String info[3] = {"te", "te"};
	I2C_Interface = "MCP";
	USB->Checked = true;

	//I2C_DRV->Init_I2C_Bus(I2C_Interface, info);
	Initial_USB_Intreface();
	USBI2C_Freq->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::NI8451Click(TObject *Sender)
{
	I2C_Interface = "NI8451";
	NI8451->Checked = true;

	Initial_USB_Intreface();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::USBI2C_FreqClick(TObject *Sender)
{
	TFreqForm *Freq_Setting = new TFreqForm(this);
	Freq_Setting->ShowModal();
	if (I2C_Interface == "USB")
		Initial_USB_Intreface();
	delete Freq_Setting;
}
//---------------------------------------------------------------------------
void __fastcall Initial_USB_Intreface()
{
	int SerialNumbers[8];
	long VersionInfo;
	AnsiString DLL_Version;
	// MainForm->USB->Checked=true;
	MainForm->USBI2C_Freq->Enabled = true;
	//  MainForm->StatusBar->Panels->Items[2]->Style=psOwnerDraw;
//	MainForm->StatusBar->Panels->Items[0]->Text = Bom99 + ".ini";
	MainForm->StatusBar->Panels->Items[1]->Text = I2C_Interface;

	// Init_GY7601(Com_port) ;
	String infor[5] = {"te", "te"};
	if (I2C_Interface == "GY7601")
	{
		infor[0] = Com_port;
	}
	else if (I2C_Interface == "NI8451")
	{
		I2C_DRV->I2C_Interface = "NI8451";
		infor[0] = "0x" + IntToHex(SlaveAddress, 2);
	}

	I2C_DRV->Init_I2C_Bus(I2C_Interface, infor);

	if (I2C_DRV->I2C_bus == true)
	{
		I2C_Interface_FLAG = true;
		I2CDriver->I2CExeStatus[0] = "Initialize " + I2C_Interface + " :Sucess! ]";
	}
	else
	{
		I2C_Interface_FLAG = false;
		I2CDriver->I2CExeStatus[0] = "Initialize " + I2C_Interface + " :FAIL ]";
		//		ShowMessage("Can't Initialize I2C Bus :" + I2C_Interface + "\n Please Check Your Hardware!");
		String buf = "无法初始化I2C通讯：" + I2C_Interface + ", \n请检查硬件连接!";
		Application->MessageBox(buf.w_str(), L"提示", MB_YESNO | MB_ICONWARNING);
	}

	MainForm->Caption = "[1.1]Device : " + I2C_Interface + " " + I2CDriver->I2CExeStatus[0];
}
//---------------------------------------------------------------------------
void __fastcall Initial_ISA_Intreface()
{
	int i;
	MainForm->ISA->Checked = true;
	MainForm->USBI2C_Freq->Enabled = false;
	I2CDriver->Initialize_PCF8584_Bus();
	MainForm->StatusBar->Panels->Items[1]->Text = I2CDriver->I2CExeStatus[0];
	MainForm->StatusBar->Panels->Items[2]->Style = psOwnerDraw;
	MainForm->Caption = "[1.1]Device : ISA_PCF8584 " + I2CDriver->I2CExeStatus[0];
	if (I2CDriver->I2CExeStatus[0] != "Initialize PCF8584 [ After reset 0x81 ]")
	{
		I2C_Interface_FLAG = false;
		String buf = "无法打开I2C通讯接口！";
		Application->MessageBox(buf.w_str(), L"提示", MB_YESNO | MB_ICONWARNING);
	}
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::LinkI2CInterfaceClick(TObject *Sender)
{
	String info[] = {"1", "2"};

	if (I2C_Interface == "GY7601")
	{
		info[0] = Com_port;
	}
	I2C_DRV->Init_I2C_Bus(I2C_Interface, info);
	if (I2C_DRV->I2C_bus == true)
	{
		I2C_Interface_FLAG = true;
		if (Read_Verify->Enabled == false)
		{
			Read_Verify->Enabled = true;
		}
		if (Write_Verify->Enabled == false)
		{
			Write_Verify->Enabled = True;
		}
	}
	else
	{
		I2C_Interface_FLAG = False;
		if (Read_Verify->Enabled == true)
		{
			Read_Verify->Enabled = false;
		}
		if (Write_Verify->Enabled == true)
		{
			Write_Verify->Enabled = false;
		}
	}

	if (I2C_DRV->I2C_bus == true)
	{
		I2C_Interface_FLAG = true;
		I2CDriver->I2CExeStatus[0] = "Initialize " + I2C_Interface + " :Success! ]";
	}
	else
	{
		I2C_Interface_FLAG = false;
		I2CDriver->I2CExeStatus[0] = "Initialize " + I2C_Interface + " :FAIL ]";
		//		ShowMessage("Can't Initialize I2C Bus :" + I2C_Interface + "\n Please Check Your Hardware!");
		String buf = "无法初始化I2C通讯：" + I2C_Interface + ", \n请检查硬件连接!";
		Application->MessageBox(buf.w_str(), L"提示", MB_YESNO | MB_ICONWARNING);
	}
	MainForm->Caption = "[1.1]Device : " + I2C_Interface + " " + I2CDriver->I2CExeStatus[0];
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::ExitClick(TObject *Sender)
{
	Close();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::None_TXTClick(TObject *Sender)
{
	TXT_Label->Caption = "Save TXT Data : None";
	None_TXT->Checked = true;
	All_TXT->Checked = false;
	PASS_TXT->Checked = false;
	FAIL_TXT->Checked = false;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::All_TXTClick(TObject *Sender)
{
	TXT_Label->Caption = "Save TXT Data : All";
	None_TXT->Checked = false;
	All_TXT->Checked = true;
	PASS_TXT->Checked = false;
	FAIL_TXT->Checked = false;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::PASS_TXTClick(TObject *Sender)
{
	TXT_Label->Caption = "Save TXT Data : PASS";
	None_TXT->Checked = false;
	All_TXT->Checked = false;
	PASS_TXT->Checked = true;
	FAIL_TXT->Checked = false;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FAIL_TXTClick(TObject *Sender)
{
	TXT_Label->Caption = "Save TXT Data : FAIL";
	None_TXT->Checked = false;
	All_TXT->Checked = false;
	PASS_TXT->Checked = false;
	FAIL_TXT->Checked = true;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::RevClick(TObject *Sender)
{
	int i, j;
	AnsiString TextBuf;
	TPasswordDlg *InputPSWD = new TPasswordDlg(this);
Retry:
	Check_Data = false;
	InputPSWD->Password->Text = "";
	int result = InputPSWD->ShowModal();

	if (result == mrOk)
	{
		if (InputPSWD->Password->Text == PassWord_str)
		{
			TRevForm *RevForm = new TRevForm(this);
			int result = RevForm->ShowModal();
			if (result == mrOk)
			{
				if (I2C_Interface == "USB")
					Initial_USB_Intreface();
			}
			delete RevForm;
			FirstTime = true;

			for (i = 0; i < Rev_Count; i++)
			{
				FRU_Data[Rev_Address + i] = RevStr.c_str()[i];
			}
			if (EEP_Mirror_Enable)
			{
				for (i = 0; i < Rev_Count; i++)
					FRU_Data[Rev_Address + i + 128] = RevStr.c_str()[i];
			}

			for (i = 0; i < 16; i++)
			{
				Source_StringGrid->Cells[i + 1][0] = IntToHex(i, 2);
				Source_StringGrid->Cells[0][i + 1] = IntToHex(i * 16, 2);
				Reading_StringGrid->Cells[i + 1][0] = IntToHex(i, 2);
				Reading_StringGrid->Cells[0][i + 1] = IntToHex(i * 16, 2);
				for (j = 0; j < 16; j++)
				{
					Source_StringGrid->Cells[j + 1][i + 1] = IntToHex(FRU_Data[i * 16 + j], 2);
					Reading_StringGrid->Cells[j + 1][i + 1] = TextBuf.sprintf("%c", FRU_Data[i * 16 + j]);
				}
			}
			Model_Name_Label0->Caption = "";
			Model_Name_Label1->Caption = "";
			Model_No_Label->Caption = "";
			Rev_Label->Caption = "";
			for (i = 0; i < Name_Count; i++)
			{
				Model_Name_Label0->Caption = Model_Name_Label0->Caption + TextBuf.sprintf("%c", FRU_Data[Name_Address + i]);
				Model_Name_Label1->Caption = Model_Name_Label1->Caption + TextBuf.sprintf("%c", FRU_Data[Name_Address + i]);
			}
			for (i = 0; i < Rev_Count; i++)
				Rev_Label->Caption = Rev_Label->Caption + TextBuf.sprintf("%c", FRU_Data[Rev_Address + i]);
			for (i = 0; i < Model_No_Count; i++)
				Model_No_Label->Caption = Model_No_Label->Caption + TextBuf.sprintf("%c", FRU_Data[Model_No_Address + i]);
		}
		else if (Application->MessageBoxA(L"密码错误???", L"请重新输入", MB_RETRYCANCEL) == 4)
			goto Retry;
	}
	delete InputPSWD;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::AddressSettingClick(TObject *Sender)
{
	TAddressForm *AddressForm = new TAddressForm(this);
	AddressForm->ShowModal();
	delete AddressForm;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::None_HEXClick(TObject *Sender)
{
	Hex_Label->Caption = "Save HEX Data : None";
	None_HEX->Checked = true;
	All_HEX->Checked = false;
	PASS_HEX->Checked = false;
	FAIL_HEX->Checked = false;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::All_HEXClick(TObject *Sender)
{
	Hex_Label->Caption = "Save HEX Data : All";
	None_HEX->Checked = false;
	All_HEX->Checked = true;
	PASS_HEX->Checked = false;
	FAIL_HEX->Checked = false;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::PASS_HEXClick(TObject *Sender)
{
	Hex_Label->Caption = "Save HEX Data : PASS";
	None_HEX->Checked = false;
	All_HEX->Checked = false;
	PASS_HEX->Checked = true;
	FAIL_HEX->Checked = false;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FAIL_HEXClick(TObject *Sender)
{
	Hex_Label->Caption = "Save HEX Data : FAIL";
	None_HEX->Checked = false;
	All_HEX->Checked = false;
	PASS_HEX->Checked = false;
	FAIL_HEX->Checked = true;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::SNDuplicateWarningClick(TObject *Sender)
{
	if (SNDuplicateWarning->Checked)
	{
		MainForm->SN_Dup_Label->Caption = "重复提示关";
		SNDuplicateWarning->Checked = false;
	}
	else
	{
		MainForm->SN_Dup_Label->Caption = "重复提示开";
		SNDuplicateWarning->Checked = true;
	}
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::WriteVerifyClick(TObject *Sender)
{
	TPasswordDlg *InputPSWD = new TPasswordDlg(this);
Retry:
	InputPSWD->Password->Text = "";
	int result = InputPSWD->ShowModal();
	if (result == mrOk)
	{
		if (InputPSWD->Password->Text == PassWord_str)
		{
			WriteOrRead = 0;
			FuncLabel->Font->Color = clFuchsia;
			FuncLabel->Caption = "Write Verify";
			Read_Verify->Visible = false;
			Write_Verify->Visible = true;
			Write_Verify->Enabled = true;
			Write_Verify->SetFocus();
			ReadVerify->Checked = false;
			WriteVerify->Checked = true;
		}
		else if (Application->MessageBoxA(L"密码错误???", L"请重新输入", MB_RETRYCANCEL) == 4)
		{
			goto Retry;
		}
	}
	delete InputPSWD;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::ReadVerifyClick(TObject *Sender)
{
	TPasswordDlg *InputPSWD = new TPasswordDlg(this);
Retry:
	InputPSWD->Password->Text = "";
	int result = InputPSWD->ShowModal();
	if (result == mrOk)
	{
		if (InputPSWD->Password->Text == PassWord_str)
		{
			WriteOrRead = 1;
			FuncLabel->Font->Color = clPurple;
			FuncLabel->Caption = "Read Verify";
			Read_Verify->Visible = true;
			Read_Verify->Enabled = True;
			Read_Verify->SetFocus();
			Write_Verify->Visible = false;
			ReadVerify->Checked = true;
			WriteVerify->Checked = false;
		}
		else if (Application->MessageBoxA(L"密码错误???", L"请重新输入", MB_RETRYCANCEL) == 4)
		{
			goto Retry;
		}
	}
	delete InputPSWD;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::None_BINClick(TObject *Sender)
{
	BIN_Label->Caption = "Save BIN  Data : None";
	None_BIN->Checked = true;
	All_BIN->Checked = false;
	PASS_BIN->Checked = false;
	FAIL_BIN->Checked = false;
}

void __fastcall TMainForm::PASS_BINClick(TObject *Sender)
{
	BIN_Label->Caption = "Save BIN  Data : PASS";
	None_BIN->Checked = false;
	All_BIN->Checked = false;
	PASS_BIN->Checked = true;
	FAIL_BIN->Checked = false;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FAIL_BINClick(TObject *Sender)
{
	BIN_Label->Caption = "Save BIN  Data : FAIL";
	None_BIN->Checked = false;
	All_BIN->Checked = false;
	PASS_BIN->Checked = false;
	FAIL_BIN->Checked = true;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::All_BINClick(TObject *Sender)
{
	BIN_Label->Caption = "Save BIN  Data : All";
	None_BIN->Checked = false;
	All_BIN->Checked = true;
	PASS_BIN->Checked = false;
	FAIL_BIN->Checked = false;
}
//---------------------------------------------------------------------------

void __fastcall Save_BINData(AnsiString RW)
{
	FILE *Data_File;
	AnsiString Dir_Name, Text_FileName;
	int i, j, Recoder_Count;
	Dir_Name = ExtractFilePath(Application->ExeName) + RW + "\\";
	if (!DirectoryExists(Dir_Name))
		CreateDir(Dir_Name);
	Dir_Name = Dir_Name + Now().FormatString("yyyymmdd") + "\\";
	if (!DirectoryExists(Dir_Name))
		CreateDir(Dir_Name);

	for (i = 1; i < 256; i++)
	{
		Recoder_Count = i;
		Text_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
						MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".bin";
		if (FileExists(Text_FileName))
		{
			DeleteFile(Text_FileName);
			Recoder_Count = i + 1;
			Text_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
							MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".bin";
			goto SaveTXTData;
		}
	}
SaveTXTData:
	if (Recoder_Count >= 255)
	{
		Recoder_Count = 1;
		Text_FileName = Dir_Name + RW + "_" + MainForm->Barcode_Label->Caption + "-" +
						MainForm->Status_Label->Caption + "-" + IntToHex(Recoder_Count, 2) + ".bin";
	}
	Data_File = fopen(Text_FileName.c_str(), "wb+");
	for (i = 0; i < 256; i++)
	{
		unsigned char kkk;
		kkk = (unsigned char)FRU_Data[i];
		fwrite(&kkk, 1, 1, Data_File);
	}

	fclose(Data_File);
}

void __fastcall TMainForm::Button3Click(TObject *Sender)
{
	// COM->CloseComport() ;
	//	Init_GY7601("COM7");
}
//---------------------------------------------------------------------------

String fruSn = "A12345678900";
int fruCnt = 0;
void __fastcall SaveSnInforToCsv(String sn, String RW)
{
#if CSV_FILE_GENERATE
	String FullStreamName = "";
	String FullCsvName = "";
	String Dir_Name = "";

	if (RW == "W")
	{
		Dir_Name = ExtractFilePath(Application->ExeName) + "WRITE\\";
		if (!DirectoryExists(Dir_Name))
			CreateDir(Dir_Name);
		FullStreamName = Dir_Name + StreamFileName;
		FullCsvName = Dir_Name + ConntCsvName;
	}
	else if (RW == "R")
	{
		Dir_Name = ExtractFilePath(Application->ExeName) + "READ\\";
		if (!DirectoryExists(Dir_Name))
			CreateDir(Dir_Name);
		FullStreamName = Dir_Name + StreamFileName;
		FullCsvName = Dir_Name + ConntCsvName;
	}

	TEST_RECORD Rcd;
	//	String sn = fruSn+IntToStr(fruCnt);

	//	String FileName ="D:\\551.bin";
	//1st Add sn and infor to union
	Rcd = FormatRcdUnion(sn);
	//2nd Add Record to Stream
	StreamAddUnion(Rcd, FullStreamName);
	//3rd Save Stream to CSV file
	TransferStreamToCsv(FullStreamName, FullCsvName);

#endif
}
//---------------------------------------------------------------------------
TEST_RECORD __fastcall FormatRcdUnion(String sn)
{
	TEST_RECORD Rcd;
	BYTE data[20] = {0};
	char *str = sn.t_str();
	memset(Rcd.tRcd, 0, sizeof(TEST_RECORD));
	int i = 0;
	//format sn to union
	for (i = 0; i < sn.Length(); i++)
	{
		Rcd.tSN[i] = str[i];
	}
	char *msg = Rcd.tSN;

	String sTime = FormatDateTime("hh:nn:ss", Now());
	char *tTime = sTime.t_str();

	String sDate = FormatDateTime("yyyy'-'mm'-'dd", Now());
	char *tDate = sDate.t_str();
	for (i = 0; i < 10; i++)
	{
		Rcd.tDate[i] = tDate[i];
	}
	for (i = 0; i < 8; i++)
	{
		Rcd.tTime[i] = tTime[i];
	}
	return Rcd;
}
#if 1
int __fastcall StreamAddUnion(TEST_RECORD Rcd, String FileName)
{
	bool SaveNewFile = False;
	TMemoryStream *readStream = new TMemoryStream();

	int MemSize = 0;
	int error_code = 0;
	if (FileExists(FileName))
	{
		try
		{
			readStream->LoadFromFile(FileName);
		}
		catch (...)
		{
			ShowMessage(" Open *.cnt File Failed !");
			return 2;
		}

		readStream->Seek(0, soFromEnd);
		if (readStream->Size % sizeof(TEST_RECORD) != 0)
		{
			error_code = 1; //the file size has been changed .
			return error_code;
		}
		readStream->WriteBuffer(&Rcd, sizeof(Rcd));
	}
	else
	{
		SaveNewFile = true;
		readStream->Seek(0, soFromBeginning);
		readStream->WriteBuffer(&Rcd, sizeof(Rcd));
	}
	readStream->SaveToFile(FileName);
	readStream->Clear();

	delete readStream;
	return error_code;
}
//---------------------------------------------------------------------------
void __fastcall TransferStreamToCsv(String StreamFile, String CsvFile)
{
	TMemoryStream *readStream = new TMemoryStream();
	int stmSize = 0;
	long i = 0;
	TEST_RECORD Rcd;
	String str = "SN Number,Date,Time\n";
	if (FileExists(StreamFile))
	{
		readStream->LoadFromFile(StreamFile);
		readStream->Seek(0, soFromBeginning);
		if (readStream->Size % sizeof(TEST_RECORD) != 0)
		{
			ShowMessage("The Data File Is not Correct!");
			return;
		}
		stmSize = readStream->Size / sizeof(Rcd);
		for (i = 0; i < stmSize; i++)
		{
			readStream->Seek(0, soFromCurrent);
			readStream->ReadBuffer(&Rcd, sizeof(Rcd));
			str += RcdToString(Rcd);
		}
	}
	else
	{
		ShowMessage("Canot Find the Correct File !!");
		return;
	}
	//	TMemo *mmo;// =new TMemo();
	MainForm->memo->Text = str;
	MainForm->memo->Lines->SaveToFile(CsvFile);
	MainForm->memo->Lines->Clear();
	//delete mmo;
}
//---------------------------------------------------------------------------
String RcdToString(TEST_RECORD Rcd)
{
	char *sSn = Rcd.tSN;
	char *sDt = Rcd.tDate;
	char *sTm = Rcd.tTime;

	String SN = sSn;
	String DT = sDt;
	String TM = sTm;

	String str = "";
	str = SN.SubString(0, 14) + ",";
	str += DT.SubString(0, 10) + ",";
	str += TM.SubString(0, 8) + "\r\n";

	return str;
}
#endif
//---------------------------------------------------------------------------

void __fastcall TMainForm::Edit1Click(TObject *Sender)
{
	TfrmMes *fm = new TfrmMes(this);
	fm->ShowModal();
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ckiMesOffLineClick(TObject *Sender)
{
	AnsiString TextBuf;
	TPasswordDlg *InputPSWD = new TPasswordDlg(this);
Retry:
	Check_Data = false;
	InputPSWD->Password->Text = "";
	int result = InputPSWD->ShowModal();
	if (result == mrOk)
	{
		if (InputPSWD->Password->Text == "ASPOWER")
		{
			if (ckiMesOffLine->Checked == true)
			{
				ckiMesOffLine->Checked = false;
				IpcMes->bMesIsEnabed = false;
				MainForm->StatusBar->Panels->Items[2]->Text = "MES OffLine";
			}
			else
			{
				ckiMesOffLine->Checked = true;
				IpcMes->bMesIsEnabed = true;
				MainForm->StatusBar->Panels->Items[2]->Text = "MES OnLine";
			}
		}
		else
		{
			ShowMessage("Code is not right ,Nothing Will Change !");
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::UnlockClick(TObject *Sender)
{

	if (MainForm->Unlock->Checked == false)
	{
		EnableAspowerEepUnlock = true;
		MainForm->Unlock->Checked = true;
	}
	else
	{
		EnableAspowerEepUnlock = false;
		MainForm->Unlock->Checked = false;
	}
}
String __fastcall TMainForm::Get99ModelNumber(String SN)
{
	String Bom;
    if (mniGetBom2->Checked)
    {
    	Bom = Get99ModelNumber2(SN);
        return Bom;
    }
	String ConnString = "Provider=SQLOLEDB.1;Persist Security Info=False;\User ID=%s;\Initial Catalog=SKTMES_OLT_Prod;\Data Source=%s;\Password=%s";
	String StrConnect = Format(ConnString, ARRAYOFCONST((IpcMes->sAccount, IpcMes->sServerID, IpcMes->sPassword)));
//    StrConnect = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=SKTMES_OLT_Prod;Data Source=172.16.0.232\\oltmes;Password=Olt2016@skt";

    sp1->ConnectionString = StrConnect;
    sp1->ProcedureName = "IPC_FindItemCode";
	if(sp1->Parameters->Count == 0)
	{
	    sp1->Parameters->CreateParameter(L"SN", ftString, pdInput, 50, fgUnassigned);
	    sp1->Parameters->CreateParameter(L"ProjectName", ftString, pdReturnValue, 200, fgUnassigned);
	}

    sp1->Parameters->ParamByName(L"SN")->Value = SN;
    sp1->Close();
    sp1->ExecProc();

    Bom = VarToStr(sp1->Parameters->ParamByName(L"ProjectName")->Value);
    return Bom;
}
//---------------------------------------------------------------------------
String __fastcall TMainForm::Get99ModelNumber2(String SN)
{
    String BomNumber = Bom99;
	if (SN.Length() == SN_Count) {
    	GetItemCode* ItemInfo = new GetItemCode();
        ItemInfo->SN = SN;
		try
        {
            GetItemCodeResponse* pRe = SaveFileService->GetItemCode(ItemInfo);
            BomNumber = pRe->GetItemCodeResult;
        }
        catch (...)
    	{
        	Application->MessageBoxA(L"获取料号错误", L"Error", MB_OK|MB_ICONWARNING);
            if (Bom99.Length() != 18)
            	Application->MessageBoxA(L"ini99料号错误，请核查！", L"Error", MB_OK|MB_ICONWARNING);
            else
            	BomNumber = Bom99;
        }
        delete ItemInfo;
    }

    return BomNumber;
}
//---------------------------------------------------------------------------
String __fastcall TMainForm::Get91From99(String Bom99)
{
	String Bom91 = "";
	if (Bom99.Length() == 18)
    {
    	GetNewItemCode *Item = new GetNewItemCode();
        Item->OldItemNo = Bom99;
        try {
            GetNewItemCodeResponse *pRe = SaveFileService->GetNewItemCode(Item);
        	Bom91 = pRe->GetNewItemCodeResult;
        } catch (...) {
        	Application->MessageBoxA(L"获取料号错误", L"Error", MB_OK|MB_ICONWARNING);
        }
        delete Item;
    }
    return Bom91;
}
//---------------------------------------------------------------------------
String __fastcall TMainForm::Get99From91(String Bom91)
{
	if (Bom91.Length() == 15)
    {
    	GetOldItemCode *Item = new GetOldItemCode();
        Item->newItemNo = Bom91;
        try {
            GetOldItemCodeResponse *pRe = SaveFileService->GetOldItemCode(Item);
        	Bom99 = pRe->GetOldItemCodeResult;
        } catch (...) {
        	Application->MessageBoxA(L"获取料号错误", L"Error", MB_OK|MB_ICONWARNING);
        }
        delete Item;
    }
    return Bom99;
}
//---------------------------------------------------------------------------
bool __fastcall TMainForm::IsPacked(String SN)
{
	String ConnString = "Provider=SQLOLEDB.1;Persist Security Info=False;\User ID=%s;\Initial Catalog=SKTMES_OLT_Prod;\Data Source=%s;\Password=%s";
	String StrConnect = Format(ConnString, ARRAYOFCONST((IpcMes->sAccount, IpcMes->sServerID, IpcMes->sPassword)));
	//    StrConnect = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=SKTMES_OLT_Prod;Data Source=172.16.0.232\\oltmes;Password=Olt2016@skt";

	sp1->ConnectionString = StrConnect;
	sp1->ProcedureName = "uspFruGetSNPacking";
	if (sp1->Parameters->Count == 0)
	{
		sp1->Parameters->CreateParameter(L"SN", ftString, pdInput, 50, fgUnassigned);
		sp1->Parameters->CreateParameter(L"Msg", ftString, pdReturnValue, 200, fgUnassigned);
	}

	sp1->Parameters->ParamByName(L"SN")->Value = SN;
	sp1->Close();
	sp1->ExecProc();

	String Bom = VarToStr(sp1->Parameters->ParamByName(L"Msg")->Value);

	return Bom == L"YES";
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::mniAboutClick(TObject *Sender)
{
	TAboutBox *form = new TAboutBox(this);
	form->lblName->Caption = Application->Title.UpperCase();
	form->lbl99ModelNumber->Caption = Bom99;
    form->lblModelNumber->Caption = "50200213";
    form->lblDateFirst->Caption = "2021-03-08";
	form->lblDateLast->Caption = Date_Compiled;
	form->lblAddress->Caption = Address_Enum;
	TReplaceFlags rf = TReplaceFlags() << rfReplaceAll;
	form->mmoTips->Text = StringReplace(sTips, L"\\n", L"\r\n", rf);
	form->ShowModal();
	delete form;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::mniOpenDirClick(TObject *Sender)
{
	AnsiString disk = ExtractFileDrive(Application->ExeName);
	AnsiString Dir_Name = ExtractFilePath(Application->ExeName) + "WRITE\\" + FormatDateTime("yyyymmdd",Now());
    if (!DirectoryExists(Dir_Name))
    	Dir_Name = ExtractFileDir(Application->ExeName);
	AnsiString path = "explorer.exe " + Dir_Name;
//	AnsiString path = "explorer.exe " + ExtractFileDir(Application->ExeName);
	//path = "explorer.exe  \\\\Prd\\ipc工程部\\TE";
    STARTUPINFO si = {0};
    PROCESS_INFORMATION pi = {0};
    si.dwFlags = 1;
    si.wShowWindow = true;
    char* sCmdLine = path.c_str();
    char* sOutputDir = disk.c_str();
    bool bRet = CreateProcessA(NULL,sCmdLine,NULL,NULL,false,0x10,NULL,sOutputDir,&si,&pi);
}
//---------------------------------------------------------------------------
String __fastcall GetFileHeader(String SN, String sResult, String Path)
{
	String buf;
    String Bom = Bom99;
    if (IpcMes->bMesIsEnabed)
	{
    	Bom = MainForm->Get99ModelNumber(SN);
    }
    String header = L"标题：" + MainForm->Model_Name_Label0->Caption + "\n";
    buf.sprintf(L"结果：%s\n", sResult.w_str());
    header += buf;
    buf.sprintf(L"SN: %s\n料号：%s\n", SN.w_str(), Bom.w_str());
    header += buf;
    header += GetHostInfo();
    buf.sprintf(L"日期时间：%s\n", Now().FormatString("yyyy-mm-dd HH:MM:SS").w_str());
    header += buf;
    buf = MainForm->StatusBar->Panels->Items[3]->Text;
    buf.sprintf(L"本机路径：%s\n软件版本：%s\n编译日期：%s\n", Path.w_str(), buf.w_str(), Date_Compiled.w_str());
    header += buf;

    return header;
}

String __fastcall GetHostInfo()
{
	AnsiString IP, info;
    WSADATA wsaData;

	int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (ret != 0)
	{
		return info;
	}

	char hostname[256] = {0};
	ret = gethostname(hostname, sizeof(hostname));
	if (SOCKET_ERROR == ret)
	{
		return info;
	}
	HOSTENT *pHost = gethostbyname(hostname);
	if (NULL == pHost)
	{
		info = hostname;
		return info;
	}

	if (hostIP.Length() < 5)
	{
		for (int i = 0; pHost != NULL && pHost->h_addr_list[i] != NULL; i++)
		{
			IP = inet_ntoa(*(in_addr *)pHost->h_addr_list[i]);
		}
	}
	else
	{
		IP = hostIP;
	}
	//            "Date Compiled     :"
	info.sprintf("机名：%s\n本机IP：%s\n", hostname, IP.c_str());
	WSACleanup();
	return info;
}

void __fastcall FileUpload()
{
	String Path = ExtractFilePath(Application->ExeName) + L"TaskTemp.txt";
	String buf;
    AnsiString sbuf;

	if (FileExists(Path))
	{
		//读取文件
		std::auto_ptr<TStringList> Tskls(new TStringList);
		TStreamReader *reader = new TStreamReader(Path);
		while ((buf = reader->ReadLine()) != NULL)
		{
			if (buf.Length() > 40)
			{
				Tskls->Add(buf);
			}
			else
				break;
		}
		delete reader;
		//清空文件
        sbuf = Path;
		FILE *fp = fopen(sbuf.c_str(), "w");
		if (NULL != fp)
			fclose(fp);
		//依次上传文件
		for (int i = 0; i < Tskls->Count; i++)
		{
			std::auto_ptr<TStringList> s1(new TStringList);
			s1->Delimiter = L',';
			s1->StrictDelimiter = true;
			s1->DelimitedText = Tskls->Strings[i];
			MainForm->mniUploadLog->Checked = CUploadLogService(s1->Strings[0], s1->Strings[1]);
		}
	}
}

//99PAK10150I0480121 15 R253A2124144090  WP 01 20211216115021 01.txt
String __fastcall GetUploadFileName(String SN, bool bResult)
{
	AnsiString Bomb, sn, wr, res, LogType, time, FileName;

    Bomb = Bom99;
    sn = SN;
	if (MainForm->mniUploadLog->Checked)
	{
		Bomb = MainForm->Get99ModelNumber(SN);
        if (Bomb.Length() == 15)
        {
        	Bom99 = MainForm->Get99From91(Bomb);
            if (Bom99.Length() == 18)
            {
	            Bomb = Bom99;
            }
            else
            {
                Bomb = "990" + Bomb;
            }
        }
	}
	wr = MainForm->WriteVerify->Checked ? "W" : "R";
	res = bResult ? "P" : "F";
	LogType = "23";
	if (IpcMes->sSttion == L"I037-IPC条码信息验证")
	{
		LogType = "24";
	}
    time = Now().FormatString("yyyymmddHHMMSS");
	FileName.sprintf("%s%d%s%s%s%s%s01.txt", Bomb.c_str(), sn.Length(), sn.c_str(), wr.c_str(), res.c_str(), LogType.c_str(), time.c_str());
	return FileName;
}

void __fastcall LogStoreTask(String FileName, String SourcePath)
{
	TStreamWriter *writer;
	String FilePath = ExtractFilePath(Application->ExeName) + "TaskTemp.txt";
	writer = new TStreamWriter(FilePath, true);
	writer->WriteLine(FileName + "," + SourcePath);
	delete writer;
}

_di_ServiceSaveFileSoap TMainForm::GetServiceSaveFileSoap()
{
	if (!ServiceSaveFile)
	{
		htpr1->QueryInterface(ServiceSaveFile);
	}
	return ServiceSaveFile;
}

bool __fastcall CUploadLogService(String FileName, String SourcePath)
{
	UTF8String u8Str;
	String buf = "";
	if (FileExists(SourcePath))
	{
		if (MainForm->mniUploadLog->Checked)
		{
			int hf = FileOpen(SourcePath, fmOpenRead | fmShareDenyNone);
			if (hf > 0)
			{
				int len = FileSeek(hf, 0, 2);
				FileSeek(hf, 0, 0);
				char buffer[4096] = {0};
				len = FileRead(hf, buffer, 4096);
				buf = buffer;
				u8Str = buf;
				PMLogSave->FileName = FileName;
				PMLogSave->FileData = u8Str.BytesOf();
				try
				{
					PLogRet = MainForm->SaveFileService->SaveAtRemoteFolder(PMLogSave);
					buf = PLogRet->SaveAtRemoteFolderResult;
				}
				catch (...)
				{
					buf = L"网络异常！";
				}
			}
			FileClose(hf);
			if (buf == "ok")
			{
				return true;
			}
			else
			{
				LogStoreTask(FileName, SourcePath);
			}
		}
		else
		{
			LogStoreTask(FileName, SourcePath);
		}
	}
	return false;
}

String __fastcall GetDateCompiled()
{
    const char* pMonth[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    const char Date[12] = __DATE__;
    int i, year, month, day;
    AnsiString buf;

    for (i = 0; i < 12; i++)
    {
        if (memcmp(Date, pMonth[i], 3) == 0)
        {
            month = i + 1;
            break;
        }
    }
    year = atoi(Date + 7);
    day = atoi(Date + 4);

    buf.sprintf("%d-%d-%d %s", year, month, day, __TIME__);

    return buf;
}
//---------------------------------------------------------------------------
bool __fastcall Read2B(String& log)
{
	byte r_data[20] = {0};
	bool bRet = true;
    unsigned __int32 u32Ret, u32Sample;

	I2C_DRV->PMBus_Block_Read(SlaveAddress, 0x2B, 4, r_data);
    u32Ret = r_data[3] * 16777216 + r_data[2] * 65536 + r_data[1] * 256 + r_data[0];
    u32Sample = StrToInt64("0x" + Mark2B);
    if (u32Ret != u32Sample)
    {
    	Sleep(1000);
        I2C_DRV->PMBus_Block_Read(SlaveAddress, 0x2B, 4, r_data);
    	u32Ret = r_data[3] * 16777216 + r_data[2] * 65536 + r_data[1] * 256 + r_data[0];
    }

    bRet = u32Ret == u32Sample;
	log.sprintf(L"\r\n2B标志位检查：实际读取：0x%X, 本应读取：0x%s ", u32Ret, Mark2B.w_str());

	return bRet;
}
